Seem to have some funny behaviour going on when I call the XMLTextWriter...
XmlTextWriter writer = new XmlTextWriter(targetFileName, Encoding.UTF8);
writer.WriteValue("< ?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.WriteString(Environment.NewLine);
writer.WriteStartElement("video","UploadXsd");
writer.WriteString(Environment.NewLine);
writer.WriteStartElement("title");
writer.WriteString(Environment.NewLine);
writer.WriteString(title);
writer.WriteString(Environment.NewLine);
writer.WriteEndElement();
writer.WriteString(Environment.NewLine);
writer.WriteStartElement("description");
writer.WriteString(Environment.NewLine);
writer.WriteString(description);
writer.WriteString(Environment.NewLine);
writer.WriteEndElement();
writer.WriteString(Environment.NewLine);
writer.WriteStartElement("contributor");
writer.WriteString(Environment.NewLine);
开发者_运维知识库 writer.WriteString(contributor);
writer.WriteString(Environment.NewLine);
writer.WriteEndElement();
writer.WriteString(Environment.NewLine);
writer.WriteStartElement("subject");
writer.WriteString(Environment.NewLine);
writer.WriteString(subject);
writer.WriteString(Environment.NewLine);
writer.WriteEndElement();
writer.WriteString(Environment.NewLine);
writer.WriteEndElement();
writer.WriteString(Environment.NewLine);
writer.Flush();
writer.Close();
Then I see that it is creating this:
< ?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXsd">
<title>
MyTitle
</title>
<description>
MyDescription
</description>
<contributor>
MyContributor
</contributor>
<subject>
MySubject
</subject>
</video>
Why has the writer encoded the first element into Html but not the rest?, and more to the point how do I stop it doing this? I just want to create the first element.
Why has the writer encoded the first element into Html but not the rest?
Because it is the only place you used WriteValue
how do I stop it doing this? I just want to create the first element.
The XML declaration is not an element. It is a processing instruction. Since version 1.0 and a UTF-8 encoding is the default, the simplest thing to do is to just omit it entirely. It won't make a difference to the meaning of the document, but saves you time and a few bytes.
If you really want to include it, then use WriteStartDocument
Do not use WriteValue()
, it does the encoding. Use WriteProcessingInstruction instead.
MSDN example:
XmlWriter writer = XmlWriter.Create("output.xml");
writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-16'");
writer.WriteStartElement("root");
writer.Close();
精彩评论