Dadapeer Pvg
Dadapeer Pvg

Reputation: 167

Creating XML nodes dynamically to fetch its attribute values

I'm working on this using C# .net VS 2013.

I have a scenario where I'm having the structure as below,

<td>
  <text text="abc">abc
     <tspan text = "bcd">bcd
        <tspan text = "def">def
           <tspan text = "gef">gef
           </tspan>
        </tspan>
     </tspan>
  </text>
</td>

As shown above, I don't know how many tspan nodes will be there, currently I have 3, I may get 4 or more than that.

Once after finding the text node, to get the value of that node I'll use the code,

labelNode.Attributes["text"].Value

to get its adjacent tspan node, I have to use it like

labelNode.FirstChild.Attributes["text"].Value

to get its adjacent tspan node, I have to use it like

labelNode.FirstChild.FirstChild.Attributes["text"].Value

Like this it will keep on going.

Now my question is, if I know that i have 5 tags, is there any way to dynamically add "FirstChild" 5 times to "labelNode" so that I can get the text value of the last node, like this

labelNode.FirstChild.FirstChild.FirstChild.FirstChild.FirstChild.Attributes["text"].Value

If I need 2nd value i need to add it 2 times, if I need 3rd then I need to add it thrice.

Please let me know is there any solution for this.

Please ask me, if you got confused with my question.

Thanking you all in advance.

Upvotes: 0

Views: 136

Answers (2)

Hari Prasad
Hari Prasad

Reputation: 16956

I would suggesting using Linq to Xml which has cleaner way parsing Xml

Using XElement (or XDocument) you could flatten the hierarchy by calling Descendant method and do all required queries.

ex..

XElement doc= XElement.Load(filepath);      
var results =doc.Descendants()
                .Select(x=>(string)x.Attribute("text"));

//which returns 
abc,
bcd,
def,
gef

If you want to get the last child you could simply use.

ex..

XElement doc= XElement.Load(filepath);      
doc.Descendants()                   
   .Last()  // get last element in hierarchy.
   .Attribute("text").Value  

If you want to get third element, you could do something like this.

XElement doc= XElement.Load(filepath);      
doc.Descendants()                   
   .Skip(2)  // Skip first two.
   .First()   
   .Attribute("text").Value ; 

Check this Demo

Upvotes: 1

Paolo Tedesco
Paolo Tedesco

Reputation: 57172

Rather than adding FirstChild dynamically, I think this would be a simpler solution:

static XmlNode GetFirstChildNested(XmlNode node, int level) {
    XmlNode ret = node;
    while (level > 0 && ret != null) {
        ret = ret.FirstChild;
        level--;
    }
    return ret;
}

Then you could use this function like this:

var firstChild5 = GetFirstChildNested(labelNode, 5);

Upvotes: 1

Related Questions