开发者

Linq to XML ( I am unable to access the value between the tags)

开发者 https://www.devze.com 2022-12-10 05:43 出处:网络
I need to access Values under Address Tag using linq to Xml. <p1:Person> <p2:ID>1</p2:ID>

I need to access Values under Address Tag using linq to Xml.

<p1:Person>
  <p2:ID>1</p2:ID>
  <p2:Name>Qwerty</p2:Name>
  <p2:Address>
    <p2:street>1111 abc</p2:street>
    <p2:road # >9</p2:road #>
  </p2:Address>
<p1:Person>

I wrote a query like this

ArrayList nodes = new ArrayList();
List<XElement> personNode = xml.Elements().Where(e => e.Name.LocalName == "Person").ToList();
foreach (XElement x in personNode )
{
    IEnumerable<XElement> addressNode = x.Elements().Where(e => e.Name.LocalName == "Address");
    foreach (XElement x in addressNode)
    {                
      开发者_如何学C  IEnumerable<XElement> streetNode= x.Elements().Where(e => e.Name.LocalName == "street");
        foreach (XElement x1 in streetNode)
        {
            Nodes.Add(x1.Value);
        }
    }
}

This should give me the Street Value in Nodes Arraylist.. But Error is near "addressNode".. No values are getting into addressNode variable.

Please Throw some input on this Query. That would be of great Help.

Regards, NewbietoLinq


Looks like you're trying to re-use the x variable inside the nested foreach loop. Does this work?

ArrayList nodes = new ArrayList();
List<XElement> personNode = xml.Elements().Where(e => e.Name.LocalName == "Person").ToList();
foreach (XElement p in personNode )
{
    IEnumerable<XElement> addressNode = p.Elements().Where(e => e.Name.LocalName == "Address");
    foreach (XElement a in addressNode)
    {                
        IEnumerable<XElement> streetNode= a.Elements().Where(e => e.Name.LocalName == "street");
        foreach (XElement s in streetNode)
        {
            Nodes.Add(s.Value);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消