简体   繁体   中英

XML get value from nextNode

I am trying to get a value from a node after my selected node. So far I have been able to get the whole node info as a var but I am stuck on how to get only the value out.

my xml looks like so

<COLUMN>
<NAME>Addr1</NAME>
<VALUE>1234 my street</VALUE>
</COLUMN>

and I getting the node like this

var address = (from c in contactInfo.Descendants("NAME")
                                   where c.Value == "Addr1"
                               select c.NextNode).Single();

Thanks

尝试:

(address as XElement).Value

NextNode returns an XNode , while you need an XElement :

var address = (from c in doc.Descendants("NAME")
    where c.Value == "Addr1"
    select c.NextNode).OfType<XElement>().Single().Value;

I would rather avoid putting it all on one line and do something like the following to add some extra checks:

var address = (from c in doc.Descendants("NAME")
                where c.Value == "Addr1"
                select c.NextNode).Single();
var element = address as XElement;
if (element != null) {
    string value = element.Value;
}
var node = contactInfo.Descendants("COLUMN")
                  .SingleOrDefault(c => c.Element("NAME").Value.Equals("Addr1"))

if (node != null)
     var result = node.Element("VALUE").Value;

You should select COLUMN element instead of searching for NAME elements:

var address = (from c in contactInfo.Descendants("COLUMN")
               where (string)c.Element("NAME") == "Addr1"
               select (string)c.Element("VALUE")).Single();

Same with method syntax:

var address = contactInfo.Descendants("COLUMN")
                         .Where(c => (string)c.Element("NAME") == "Addr1")
                         .Select(c => (string)c.Element("VALUE"))
                         .Single();

Also you should be completely sure that there always exist exactly one column element with name Addr1 . Otherwise Single() will throw an exception.

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