Question

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.

Was it helpful?

Solution

If I understand your question correctly, what you really want to do is create an OtherObject for each instance of the Head element, with the child objects representing the child Node elements.

Something like this should work:

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

    }


}

OTHER TIPS

You may want to use Linq-To-Xml instead

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top