简体   繁体   English

使用“动态”节点解析xml文档

[英]Parse an xml document with “dynamic” nodes

I am parsing XML via an XDocument , how can I retreive all languages, ie <en> or <de> or <CodeCountry> and their child elements? 我正在通过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>

As your xml document is not well formatted, you should first add a root element. 由于您的xml文档格式不正确,您应该首先添加根元素。 You may do something like that. 你可能会做那样的事情。

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

Then, as you have "dynamic top nodes", you may try to work with their children (which don't seem to be dynamic), assuming all nodes have at least a "descriptif" child. 然后,当你有“动态顶级节点”时,你可以尝试与他们的孩子(似乎不是动态的)一起工作,假设所有节点至少有一个“descriptif”孩子。 (If it's not "descriptif", it may be "prox" or "libelle") **. (如果它不是“descriptif”,它可能是“prox”或“libelle”)**。

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

Then you can select the language and childrens. 然后你可以选择语言和儿童。 I used an anonymous type, you can of course project to a custom class. 我使用匿名类型,你当然可以投射到自定义类。

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
            });

This is of course not performant code for a big file, but... that's another problem. 这当然不是大文件的高性能代码,但是......这是另一个问题。


** Worst case, you may do **最坏的情况,你可能会这样做

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));

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

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