简体   繁体   English

Linq to XML 查询返回 null

[英]Linq to XML query returns null

I have the following XML file:我有以下 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<tmx version="1.4">
  <header/>
  <body>
    <tu>
      <tuv lang="en">
        <seg>Hello?</seg>
      </tuv>
      <tuv lang="es">
        <seg>¿Diga?</seg>
      </tuv>
    </tu>
  </body>
</tmx>

And I'm trying to use this code to retrieve the content of the first <seg> tag:我正在尝试使用此代码来检索第一个<seg>标记的内容:

root.Elements("tuv")
    .Where(e => e.Attribute("lang").Value.Equals("en"))
    .Select(e => e.Elements("seg"))
    .SingleOrDefault()
    .Where(d => d.Value.Equals(originalText))
    .SingleOrDefault()
    .Value;

originaltext equals "Hello?" originaltext等于“你好?” in this case.在这种情况下。 However, the result given is null.但是,给出的结果为空。 I assume my linq query is wrong.我假设我的 linq 查询是错误的。 Could anyone give me a hint on how to write this query properly?谁能给我一个关于如何正确编写此查询的提示? Thank you very much!非常感谢!

The Elements function returns a collection of the direct child elements of the root . Elements函数返回root的直接子元素的集合。 You should use the Descendants method that return the collection of all descendant elements.您应该使用返回所有后代元素集合的Descendants方法。

root.Descendants("tuv").Where(e => e.Attribute("lang").Value == "en")
                       .Select(e => e.Elements("seg")).SingleOrDefault() 
                       .Where(d => d.Value == originalText).SingleOrDefault().Value

If you want to select the first "seg" element, do this如果要选择第一个“seg”元素,请执行此操作

var xDoc = XDocument.Parse(File.ReadAllText(@"C:\YourDirectory\sample.xml"));

var firstSeg = xDoc.Descendants("seg").First();

Code to satisfy OP's requirement in comment满足OP在评论中要求的代码

var seg = xDoc.Descendants("tuv")
                .First(tuv => tuv.Attribute("lang").Value == "en")
                .Element("seg")
                .Value;

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

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