0

I have an Xml File that looks like this:

<Head>
<Node Name="something" value="10"/>
<Node Name="somethingElse" value="3"/>
</head>
<Head>
<Node Name="something" value="10"/>
<Node Name="somethingElse" value="3"/>
</head>

What I want is to be able to create and object that contains two Objects which have a name and a key.

This is what I have so far:

public void XmlReaderMethod(string Path)
{
SomeObject object = new Object();
 using (XmlTextReader xReader = new XmlTextReader(Path))
            {
                while (xReader.Read())
                {
                    if (xReader.NodeType == XmlNodeType.Attribute)
                    {
                        if (xReader.Name == "Name")
                        {
                            object = new object(xReader.Name);

                        }
                        else if (xReader.Name == "Value")
                        {
                           object.Key = xReader.Name;
                        }
                    }
                  //For Every two objects
                  //OtherObject otherObject = new OtherObject(object1, object2);
                }
            }
         }

But what I want it to do is to take every two SomeObject created with a name and a value to create a OtherObject that contains two someObject.

4

2 回答 2

0

如果我正确理解您的问题,您真正想要做的是为元素OtherObject的每个实例创建一个Head,子对象代表子Node元素。

像这样的东西应该工作:

XmlDocument oXml = new XmlDocument();
oXml.Load(Path);

//Get a list of Head nodes. For each one of these, create an `OtherObject`
XmlNodeList headNodes = oXml.SelectNodes("//Head");

foreach(XmlNode headNode in headNodes)
{
    //Get a list of the child 'Node' nodes
    XmlNodeList childNodes = headNode.SelectNodes("./Node");

    if(childNodes.Count == 2)
    {
       Object firstObject = new Object() { 
                                            Name = childNodes[0].Attributes["Name"].Value,
                                            Key = childNodes[0].Attributes["Key"].Value 
                                         };

       Object secondObject = new Object() { 
                                            Name = childNodes[1].Attributes["Name"].Value,
                                            Key = childNodes[1].Attributes["Key"].Value 
                                         };                                      

        OtherObject oOther = new OtherObject(firstObject, secondObject);

    }


}
于 2013-06-05T12:42:20.073 回答
0

您可能想改用Linq -To-Xml

于 2013-06-05T12:42:23.133 回答