LINQ-to-XML XElement query NULL

假装没事ソ 提交于 2019-12-11 13:19:54

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/20764060/linq-to-xml-xelement-query-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!