考虑下面的简单代码,它创建一个 XML 文档并显示它。
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("root");
xml.AppendChild(root);
XmlComment comment = xml.CreateComment("Comment");
root.AppendChild(comment);
textBox1.Text = xml.OuterXml;
它按预期显示:
<root><!--Comment--></root>
但是,它不显示
<?xml version="1.0" encoding="UTF-8"?>
那么我怎样才能得到它呢?
使用 XmlDocument.CreateXmlDeclaration 方法创建 XML 声明:
XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);
注意:请查看该方法的文档,特别是对于
encoding
参数:该参数的值有特殊要求。
您需要使用 XmlWriter(默认情况下写入 XML 声明)。您应该注意到,C# 字符串是 UTF-16,而您的 XML 声明表明该文档是 UTF-8 编码的。这种差异可能会导致问题。这是一个示例,写入一个文件,给出您期望的结果:
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("root");
xml.AppendChild(root);
XmlComment comment = xml.CreateComment("Comment");
root.AppendChild(comment);
XmlWriterSettings settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
ConformanceLevel = ConformanceLevel.Document,
OmitXmlDeclaration = false,
CloseOutput = true,
Indent = true,
IndentChars = " ",
NewLineHandling = NewLineHandling.Replace
};
using ( StreamWriter sw = File.CreateText("output.xml") )
using ( XmlWriter writer = XmlWriter.Create(sw,settings))
{
xml.WriteContentTo(writer);
writer.Close() ;
}
string document = File.ReadAllText( "output.xml") ;
XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);
定义多个元素
enter code here
Dim VAs Object Set V= xmlDoc.createElement("V") V.Text = "0" rootElement.appendChild V