我想创建一个这样的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<text>
<languages>
<language id =1>English</language>
<language1 id=2>Slovenian</language1>
</languages>
<strings>
<line id=1>
<string lid=1>camera</string>
<string lid=2>kamera</string1>
</line>
<line id=2>
<string lid=1>lens</string>
<string1 lid=2>leka</string1>
</line>
</strings>
</text>
我正在尝试使用C#(Windows窗体应用程序)中的以下代码:
XmlDocument xmldoc = new XmlDocument();
XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", null, null);
xmldoc.AppendChild(xmldec);
XmlElement root = xmldoc.CreateElement("text");
xmldoc.AppendChild(root);
XmlElement lang = xmldoc.CreateElement("languages");
XmlElement languages = xmldoc.CreateElement("language");
languages.SetAttribute("id", "1");
languages.InnerText = "English";
lang.PrependChild(languages);
languages.SetAttribute("id", "2");
languages.InnerText = "Slovenian";
lang.PrependChild(languages);
XmlElement lines = xmldoc.CreateElement("strings");
XmlElement line = xmldoc.CreateElement("line");
XmlElement lineinner = xmldoc.CreateElement("string");
line.SetAttribute("id", "1");
lineinner.SetAttribute("lid", "1");
lineinner.InnerText = "some english text";
line.AppendChild(lineinner);
line.SetAttribute("id", "1");
lineinner.SetAttribute("lid", "2");
lineinner.InnerText = "some slovenian text";
line.AppendChild(lineinner);
lines.AppendChild(line);
root.AppendChild(lang);
root.AppendChild(lines);
Metodi.SerializeXMLToXML(xmldoc);
我最终得到以下结果:
<?xml version="1.0" encoding="UTF-8"?>
<text>
<languages>
<language id="2">Slovenian</language>
</languages>
<strings>
<line id="2">
<string lid="2">some slovenian text</string>
</line>
</strings>
</text>
在每个下一个AppendChild()替换之前有没有办法实现这个?
答案 0 :(得分:2)
每次重新初始化都是一个解决方案:
XmlDocument xmldoc = new XmlDocument();
XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", null, null);
xmldoc.AppendChild(xmldec);
XmlElement root = xmldoc.CreateElement("text");
xmldoc.AppendChild(root);
XmlElement lang = xmldoc.CreateElement("languages");
XmlElement languages = xmldoc.CreateElement("language");
languages.SetAttribute("id", "1");
languages.InnerText = "English";
lang.PrependChild(languages);
languages = xmldoc.CreateElement("language");
languages.SetAttribute("id", "2");
languages.InnerText = "Slovenian";
lang.PrependChild(languages);
XmlElement lines = xmldoc.CreateElement("strings");
XmlElement line = xmldoc.CreateElement("line");
XmlElement lineinner = xmldoc.CreateElement("string");
line.SetAttribute("id", "1");
lineinner.SetAttribute("lid", "1");
lineinner.InnerText = "some english text";
line.AppendChild(lineinner);
line = xmldoc.CreateElement("string");
line.SetAttribute("id", "1");
lineinner.SetAttribute("lid", "2");
lineinner.InnerText = "some slovenian text";
line.AppendChild(lineinner);
lines.AppendChild(line);
root.AppendChild(lang);
root.AppendChild(lines);
Metodi.SerializeXMLToXML(xmldoc);
节点只能有一个父节点,因此您的问题。 解决此问题的一种更好的方法可能是使用XML文字。我注意到C#不支持XML文字。这并没有改变你可以使用XML序列化或循环等以更好的方式编写它的事实。