考虑下面的简单代码,它创建一个 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"?>
那么我怎样才能得到它呢?
使用创建 XML 声明XmlDocument.CreateXmlDeclaration 方法 http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createxmldeclaration.aspx:
XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);
注意:请查看该方法的文档,尤其 for encoding
参数:该参数的取值有特殊要求。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)