简体   繁体   中英

How to iterate through each node in an XML and map each tag to a new tag in a new XML file using C#?

I need to covert an XML file (which follows a particular framework) into an OWL file (which also has an XML format). To do this conversion I need to write a C# code.

I am not able to iterate through each node in the XML file so as to map it into the new file and am also not understanding how to get the names of the tags in the existing XML.

The XML example is :

<ECClass name="Person">
    <ECAttributes>
        <ECObject ID="person1" size="20">
        </ECObject>
    </ECAttributes>
    <ECAttributes>
    </ECAttributes>
</ECClass>

I want to map it into something like this :

<Class reference="Person">
    <Property>
        <Instance ID="person1">
        </Instance>
    </Property>
    <Property>
    </Property>
</Class>

These are just examples and not the real XML.

The main problem is on how to iterate through each tag without knowing how many children it has. I read some articles but most of them targeted only a particular level. For example :

XmlNodeList nodes = root.SelectNodes("/ECClass");
foreach (XmlNode node in nodes)
{

}

I need to go through each tag one at a time till all its children are completed so that i can map the new XMl accordingly.

Thank you in advance for the help.

to parse every node in c# you can use recursion. Just pass this function the root node

public void findAllNodes(XmlNode node)
{
    CreateNode(node.name);
    foreach (XmlNode n in node.ChildNodes)
        findAllNodes(n);
} 

and you have to create a new xml file. you can use something like this:

XmlDocument xmlDoc = new XmlDocument();

Then implement the CreateNode function. It should be something like this:

public void CreateNode(string NodeName)
{
     if(NodeName == "something")
     {
         XmlNode rootNode = xmlDoc.CreateElement("something_else");
     }
     .....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM