简体   繁体   English

LINQ-to-XML XElement查询NULL

[英]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"). 我正在尝试UPDATE某个子元素(在本例中为“Regex”) WHERE其中一个子元素(“Name”)== selected name(“AccountNumber”)。

Here is a sample of my XmlDoc 这是我的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. 查询运行后,XElement,x仍为null ...我对LINQ(和Lambdas)很新,可以在这里使用一些指导。 Thanks! 谢谢!

It returns null because you Convert Element to String,not it's value.You should check child Element value like this 它返回null,因为你将元素转换为字符串,而不是它的值。你应该像这样检查子元素值

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

And i think Value returns string so ToString is redundant here just type 我认为Value返回字符串,所以ToString在这里是多余的只是类型

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM