【问题标题】:Parse an xml document with "dynamic" nodes解析带有“动态”节点的 xml 文档
【发布时间】:2016-04-06 13:38:30
【问题描述】:

我正在通过 XDocument 解析 XML,如何检索所有语言,即 <en><de><CodeCountry> 及其子元素?

<en>
  <descriptif>In the historic area, this 16th century Town House on 10,764 sq. ft. features 10 rooms and 3 shower-rooms. Period features include a spiral staircase. 2-room annex house with a vaulted cellar. Period orangery. Ref.: 2913.</descriptif>
  <prox>NOGENT-LE-ROTROU.</prox>
  <libelle>NOGENT-LE-ROTROU.</libelle>
</en>
<de>
  <descriptif>`enter code here`In the historic area, this 16th century Town House on 10,764 sq. ft. features 10 rooms and 3 shower-rooms. Period features include a spiral staircase. 2-room annex house with a vaulted cellar. Period orangery. Ref.: 2913.</descriptif>
  <prox>NOGENT-LE-ROTROU.</prox>
</de>
...
<lang>
  <descriptif></descriptif>
  <prox></prox>
  <libelle></libelle>
</lang>

【问题讨论】:

  • 有时我有 ,我必须拥有所有语言, 是动态应答
  • xml根目录下都是节点吗?是否有任何不是 兄弟?
  • 我已将您问题的文本拉到代码块上方,这使回答者更容易扫描问题并思考答案 - 这是一种称为“底线在前”的技术。希望它可以帮助您获得您正在寻找的答案。

标签: c# xml linq


【解决方案1】:

由于您的 xml 文档格式不正确,您应该首先添加一个根元素。 你可以这样做。

var content = File.ReadAllText(@"<path to your xml>");
var test = XDocument.Parse("<Language>" + content + "</Language>");

然后,由于您有“动态顶部节点”,您可以尝试使用它们的子节点(这似乎不是动态的),假设所有节点都至少有一个“descriptif”子节点。 (如果不是“descriptif”,可能是“prox”或“libelle”)**。

//this will give you all parents, <en>, <de> etc. nodes
var parents = test.Descendants("descriptif").Select(m => m.Parent);

然后您可以选择语言和儿童。 我用的是匿名类型,你当然可以投影到自定义类。

var allNodes = parents.Select(m => new
            {
                name = m.Name.LocalName,
                Descriptif = m.Element("descriptif") == null ? string.Empty : m.Element("descriptif").Value,
                Prox = m.Element("prox") == null ? string.Empty : m.Element("prox").Value ,
                Label = m.Element("libelle") == null ? string.Empty : m.Element("libelle").Value
            });

这当然不是大文件的高性能代码,但是……这是另一个问题。


** 最坏的情况,你可能会这样做

var parents = test.Descendants("descriptif").Select(m => m.Parent)
                .Union(test.Descendants("prox").Select(m => m.Parent))
                .Union(test.Descendants("libelle").Select(m => m.Parent));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多