2010-08-09 16 views
3

,我决定尝试一下教程本网站xmldoc.Childnodes.item()问题

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,但我无法弄清楚这条线是如何工作的

​​

具体来说,它根据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. 

不过,我还是真的不知道什么是“指数”是指,或者是什么项目()一样。它会向下移动还是向下移动分支?

而且,当我看着它,我认为它最终会像这样

什么,我想过会发生:

<?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> 

(格式化后加)

+0

在您投入太多时间之前,请确保您知道linq2xml(XDocument vs XmlDocument)。 XDocunent是通常首选的新API。 – 2010-08-09 18:02:37

+0

我选择XmlDocument的唯一原因是因为我无法计算出.NET 3.0中的新关键字,例如“from”。 – superlazyname 2010-08-09 18:15:16

回答

2

ChildNodes属性返回你叫什么的XmlNodeList立即孩子。 Item然后找到该列表的第n个成员。它不会递归到大孩子等。特别是,我相信在这种情况下Item(0)将返回XML声明,而Item(1)返回根元素。表达“获得根元素”的更好方法是使用XmlDocument.DocumentElement

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

说实话,这不是一个非常好的使用它 - 特别是我会建议使用LINQ到XML而不是XmlDocument,如果你可能的话。使用你提供的代码试图达到的目标并不是特别清楚,但是在LINQ to XML中它几乎可以肯定是更简单。

+0

至于这个代码的使用,我所做的只是在练习XML – superlazyname 2010-08-09 18:05:06

+0

@jwaffe:我建议你练习LINQ to XML而不是'XmlDocument' :) – 2010-08-09 18:08:42

+0

你知道我在哪里可以很好地解释新关键字.net 3.0? MSDN网站有一个错误,我很难找到定义 – superlazyname 2010-08-09 18:19:52