代码之家  ›  专栏  ›  技术社区  ›  smashbourne

使用LINQ to XML分析深度嵌套的属性时出现问题

  •  2
  • smashbourne  · 技术社区  · 15 年前

    我一直试图用C语言解析这个XML#

    <schema uri=http://blah.com/schema >
       <itemGroups>
         <itemGroup description="itemGroup1 label="itemGroup1">
           <items>
            <item description="The best" itemId="1" label="Nutella"/>
            <item description="The worst" itemId="2" label="Vegemite"/>
           </items>
         </itemGroup>
       </itemGroups>
    </schema>
    
    \itemGroup1\Nutella-The best
    \itemGroup1\Vegemite-The worst
    

    如有任何帮助或指示,我们将不胜感激。

    1 回复  |  直到 15 年前
        1
  •  6
  •   Rex M    15 年前
    XDocument xDoc = XDocument.Load(myXml); //load your XML from file or stream
    
    var rows = xDoc.Descendants("item").Select(x => string.Format(
                        @"\{0}-{1}\{2}-{3}",
                        x.Ancestors("itemGroup").First().Attribute("description").Value,
                        x.Ancestors("itemGroup").First().Attribute("label").Value,
                        x.Attribute("label").Value,
                        x.Attribute("description").Value));
    

    让我们来分解一下我们正在做的事情:

    • xDoc.Descendants("item") 得到我们所有 <item> 整个文档中的元素

    • Select(x => string.Format(format, args) 项目 每个 <项目& GT; 我们从上一个操作得到了lambda中指定的任何格式。在这种情况下,A formatted string .

    • 就XML树而言,我们“坐在”了 <项目& GT; 级别,因此我们需要回滚树以使用 Ancestors . 因为这个方法返回一系列元素,所以我们知道我们需要第一个(离我们最近的),这样我们就可以读取它的属性。

    现在你有了 IEnumerable<string> 一个 <项目& GT; 在XML文档和指定格式的信息中:

    foreach(string row in rows)
    {
        Console.WriteLine(row);
    }