Xmldoc.Childnodes.item () question

I decided to try the tutorial on this site

http://www.csharphelp.com/2006/05/creating-a-xml-document-with-c/

Here is my code that is more or less the same but a little easier to read

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);
    }
}

While I like XmlDocument, but I can’t understand how this line works

XmlDoc.ChildNodes.Item(1).AppendChild(element2);

In particular, the Item () element of this

according to 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.

However, I'm still not quite sure what “index” means, or what Item () does. Does he move down a tree or down a branch?

Also, when I looked at it, I thought it would end like this:

what i thought:

<?xml version="1.0"?>
<ROOT>this is the text of the root element</ROOT>
<AnotherElement>This is the text of this element</AnotherElement>

but it ended like this:

Actual output

<?xml version="1.0"?>
<ROOT>this is the text of the root element
      <AnotherElement>This is the text of this element</AnotherElement>
</ROOT>

(formatting added)

+3
source share
1

ChildNodes XmlNodeList , . Item n- . grand-children .. , , Item(0) XML, Item(1) . " " - XmlDocument.DocumentElement.

, "" . XML- XML .

, , , , LINQ to XML, XmlDocument, . , , , LINQ to XML .

+2

Source: https://habr.com/ru/post/1758782/


All Articles