简体   繁体   English

Linq to xml如何在C#中按值获取XElement

[英]Linq to xml how to get XElement by value in c#

I have an xml: 我有一个xml:

<?xml version="1.0" encoding="utf-8"?>
<Fields>
  <Field>
    <Name>DEMOFIELD</Name>
    <Category>HardwareSoftwareRequirement</Category>
  </Field>
</Fields>

When I do this: 当我这样做时:

XElement xDoc = XElement.Load("File.xml");                
var x= xDoc.Descendants("Field").Where(elem => elem.Value == "DEMOFIELD");//returns no element

This is not returning anything. 这没有返回任何东西。 But when I instead do this: 但是当我改为这样做时:

var x= xDoc.Descendants("Field").Where(elem => elem.Value.Contains( "DEMOFIELD"));//returns no element

On iteration, instead of e.Value , it returns: DEMOFIELDHardwareSoftwareRequirement , can't it just be DEMOFIELD ? 迭代的,而不是e.Value ,它返回: DEMOFIELDHardwareSoftwareRequirement ,不能只是被DEMOFIELD

And then iterate through to get the value, 然后遍历获取价值,

foreach(XElement e in x)
{
    _log.Debug(e.Value);//no value here
}

You need to be sure you are comparing the value of the right elements, it's easy to get this wrong with nested XML. 您需要确保比较的是正确元素的值,使用嵌套XML容易出错。 In your case, you are comparing the Field element's value (which will be all of the inner values concatenated), but you mean to compare it to the Name element. 在您的情况下,您正在比较Field元素的值(它将是所有内部值的串联),但是您的意思是将其与Name元素进行比较。

Try this: 尝试这个:

var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Fields>
  <Field>
    <Name>DEMOFIELD</Name>
    <Category>HardwareSoftwareRequirement</Category>
  </Field>
</Fields>";
var xdoc = XDocument.Load(new StringReader(xml));
var x = xdoc.Descendants("Field").Where(elem => elem.Element("Name")?.Value == "DEMOFIELD");

You still have the Field element now, so you if you want to get the category you'll need to do something like: 现在,您仍然具有Field元素,因此,如果要获取类别,则需要执行以下操作:

x.First().Element("Category").Value

Code in the post gets node by value, but it is not the node you are looking for. 帖子中的代码按值获取节点,但它不是您要查找的节点。

xDoc.Descendants("Field") selects all nodes named "Field", but that node has only child nodes. xDoc.Descendants("Field")选择所有名为“ Field”的节点,但是该节点只有子节点。 So when you call .Value on that node the value is computed by concatenation of all children's values ("DEMOFIELD" + "HardwareSoftwareRequirement" = "DEMOFIELDHardwareSoftwareRequirement"). 因此,当您在该节点上调用.Value时,该值是通过所有子级值(“ DEMOFIELD” +“ HardwareSoftwareRequirement” =“ DEMOFIELDHardwareSoftwareRequirement”)的串联来计算的。

Depending on what you actually looking for you either need to select all "Name" nodes and filter by value or check value of child node called "Name": 根据您实际寻找的内容,您需要选择所有“名称”节点并按值进行过滤或检查称为“名称”的子节点的值:

  var nameByValue = xDoc.Descendants("Name")
        .Where(elem => elem.Value == "DEMOFIELD");
  var fieldByChildValue = xDoc.Descendants("Field")
        .Where(elem => elem.Element("Name").Value == "DEMOFIELD");

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

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