3

我决定试试这个网站上的教程

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>

(添加格式)

4

1 回答 1

2

ChildNodes属性返回您调用它XmlNodeList直接子级的。Item然后找到该列表的第 n 个成员。它不会递归到孙子等。特别是,我相信在这种情况下Item(0)会返回 XML 声明,并Item(1)返回根元素。表达“到达根元素”的更好方法是使用XmlDocument.DocumentElement.

请注意,您的“预期”输出甚至不是有效的 XML - XML 文档只能有一个根元素。

老实说,这并不是一个非常好的使用它 - 特别是我会建议使用 LINQ to XML,而不是XmlDocument如果可能的话。目前还不清楚您要使用您给出的代码实现什么,但几乎可以肯定在 LINQ to XML 中它会简单得多

于 2010-08-09T18:01:09.020 回答