我要使用以下代码:
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
WriteXmlFile("PartNew", doc);
}
public static void WriteXmlFile(string nextItem, XmlDocument doc)
{
XmlElement root = doc.DocumentElement;
XmlElement id = doc.CreateElement(nextItem);
id.SetAttribute("Part", nextItem);
doc.DocumentElement.AppendChild(id);
root.AppendChild(id);
}
问题是我收到一条错误消息,提示我的DocumentElement为null。这是我收到错误消息doc.DocumentElement.AppendChild(id);
的行。我用谷歌搜索,但没有发现类似的情况。我想让我的代码运行什么?
错误消息:
对象DocumentElement上的NullReferenceException
答案 0 :(得分:2)
您没有创建根元素。
XmlDocument doc = new XmlDocument();
XmlNode rootNode = doc.CreateElement("root");
doc.AppendChild(rootNode);
答案 1 :(得分:0)
您可以使用支持LINQ的XDocument:代替使用XmlDocument以及添加XML声明的所有这些操作:
var xml = new XDocument(
new XDeclaration("1.0","utf-8", "yes"),
new XElement("root",
new XElement("PartNew", new XAttribute("Part", "1"))));
Console.WriteLine(xml.Declaration.ToString() + "\n" + xml.ToString());
输出:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<PartNew Part="1" />
</root>
您可以应用LINQ来创建元素:
var xml2 = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("root",
from x in new[] {1, 2, 3}
select new XElement("PartNew", new XAttribute("Part", x))));
Console.WriteLine(xml2.Declaration.ToString() + "\n" + xml2.ToString());
输出:
<root>
<PartNew Part="1" />
<PartNew Part="2" />
<PartNew Part="3" />
</root>