我决定试试这个网站上的教程
http://www.csharphelp.com/2006/05/creating-a-xml-document-with-c/
这是我的代码,或多或少相同,但更容易阅读
using System;
using System.Xml;
public class Mainclass
{
public static void Main()
{
XmlDocument XmlDoc = new XmlDocument();
XmlDocument xmldoc;
XmlNode node1;
node1 = XmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
XmlDoc.AppendChild(node1);
XmlElement element1;
element1 = XmlDoc.CreateElement("", "ROOT", "");
XmlText text1;
text1 = XmlDoc.CreateTextNode("this is the text of the root element");
element1.AppendChild(text1);
// appends the text specified above to the element1
XmlDoc.AppendChild(element1);
// another element
XmlElement element2;
element2 = XmlDoc.CreateElement("", "AnotherElement", "");
XmlText text2;
text2 = XmlDoc.CreateTextNode("This is the text of this element");
element2.AppendChild(text2);
XmlDoc.ChildNodes.Item(1).AppendChild(element2);
}
}
到目前为止,我喜欢 XmlDocument,但我不知道这条线是如何工作的
XmlDoc.ChildNodes.Item(1).AppendChild(element2);
具体来说,它的 Item() 部分
根据 MSDN...
//
// Summary:
// Retrieves a node at the given index.
//
// Parameters:
// index:
// Zero-based index into the list of nodes.
//
// Returns:
// The System.Xml.XmlNode in the collection. If index is greater than or equal
// to the number of nodes in the list, this returns null.
但是,我仍然不确定“索引”指的是什么,或者 Item() 是做什么的。它是顺着树还是顺着树枝移动?
还有,我看的时候还以为会是这个样子
我认为会发生的事情:
<?xml version="1.0"?>
<ROOT>this is the text of the root element</ROOT>
<AnotherElement>This is the text of this element</AnotherElement>
但结果是这样
实际输出
<?xml version="1.0"?>
<ROOT>this is the text of the root element
<AnotherElement>This is the text of this element</AnotherElement>
</ROOT>
(添加格式)