简体   繁体   中英

LINQ-to-XML XElement query NULL

I am trying to UPDATE a child element of something (in this case, "Regex") WHERE one of the child elements ("Name") == selected name ("AccountNumber").

Here is a sample of my XmlDoc

<?xml version="1.0" encoding="utf-8"?>
<Bill>
  <Element>
    <Name>AccountNumber</Name>
    <Regex></Regex>
    <Left></Left>
    <Right></Right>
    <Top></Top>
    <Bottom></Bottom>
    <Relations></Relations>
  </Element>
  <Element>
    <Name>BillDate</Name>
    <Regex></Regex>
    <Left></Left>
    <Right></Right>
    <Top></Top>
    <Bottom></Bottom>
    <Relations></Relations>
  </Element>
</Bill>

and here is the code I have so far.

XElement x = XmlDoc.Element("Bill")
                    .Elements("Element")
                    .Where(xel => xel.Element("Name").ToString() == CurrentSelection.ElementName)
                    .SingleOrDefault();
                x.Element("Regex").Value = details[1].Value;

After the query runs, the XElement, x, is still null... I am very new to LINQ (and Lambdas) and could use a little guidance here. Thanks!

It returns null because you Convert Element to String,not it's value.You should check child Element value like this

xel.Element("Name").Value.ToString() == CurrentSelection.ElementName

And i think Value returns string so ToString is redundant here just type

xel.Element("Name").Value == CurrentSelection.ElementName

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