Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - XML reading child nodes

I have an XML document and I am trying to get the childnodes of an element called Unit

My XML Doc is layed out like so:

<Unit>
    <id>3</id>
    <name>System Information</name>
    <description>null</description>
    ... other ...
</Unit>

This is the code I am using to try and read them.

public void Load()
{
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    XmlDocument xmldoc = new XmlDocument();
    XmlNodeList xmlnode;

    xmldoc.Load(fs);
    xmlnode = xmldoc.GetElementsByTagName("Units");

    for (int i = 0; i < xmlnode.Count; i++)
    {
        string str = string.Format("ID: {0}
Name:{0}", xmlnode[i].ChildNodes.Item(0).InnerText, xmlnode[i].ChildNodes.Item(1).InnerText);
        MessageBox.Show(str);
    }
}

But the problem is, when I try and get them, instead of getting item 0 or item 1, it displays all the items and not the items i have selected.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I can see from your xml and code. You have error in line:

 xmlnode = xmldoc.GetElementsByTagName("Units");

change it on:

 xmlnode = xmldoc.GetElementsByTagName("Unit");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...