如何遍历具有相同元素的xml文档?

时间:2016-03-05 22:35:14

标签: c# xml linq asp.net-mvc-4 linq-to-xml

我有以下xml文件

<Universe id="123nebula" name="winterfell"  parentId="0">
  <planet id="gio234" name="bobka grantos">
    <planet id="tyu88" name="viola winter" description="dgdgdddgddgdddgd"/>
  </planet>
  <planet id="huio90" name="bintor nardi" description="dedededddddddddd"/>
  <planet id="ruil99" name="torian fartknox" description="llllklklklkkllk"/>
  <planet id="huy7777" name="vivalid durol" description="ppppppppppssssss"/>
  <planet id="fila7866" name="hella fella dorrrah">
    <planet id="asaaa23" name="Sixty two nine pine" description="ffffffffdfdfd"/>
    <planet id="tyu88" name="viola winter" description="dgdgdddgddgdddgd"/>
    <planet id="juiiko8" name="tae bo" description="jujujioooppoiiu"/>
  </planet>
</Universe>

在这里,一些行星由他们自己组成,一些行星有子行星。由于所有父行星和子行星具有相同的元素名称'planet',因此识别父行星的唯一方法是查找 description attribute,其中只有子(子)行星具有“ description attribute

我想做两件事:

  1. 我需要获得id = fila7866
  2. 的父行星的所有子行星
  3. 我想得到所有没有儿童星球的行星
  4. 更新 这需要使用LINQ-2-XML来完成!

    我该怎么做?

1 个答案:

答案 0 :(得分:0)

试试这个......

using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        // Deserialize single instance
        XmlSerializer serializerSingle = new XmlSerializer(typeof(Universe));//, new XmlRootAttribute("document"));
        using (FileStream stream = File.OpenRead(@"<Path to your XML data>\planet.xml"))
        {
            // 'ReadXML.Xml2CSharp.Document' is the 'Document' class in your XML Classes
            Universe dezerializedXMLSingle = (Universe)serializerSingle.Deserialize(stream);

            var SubPlanets = (from p in dezerializedXMLSingle.Planet where p.Id == "fila7866" select p.Planets).ToList();

        } // Put a break-point here, then mouse-over dezerializedXMLSingle
    }
}
}

[XmlRoot(ElementName="planet")]
public class Planet {
    [XmlAttribute(AttributeName="id")]
    public string Id { get; set; }
    [XmlAttribute(AttributeName="name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName="description")]
    public string Description { get; set; }
    [XmlElement(ElementName="planet")]
    public List<Planet> Planets { get; set; }
}

[XmlRoot(ElementName="Universe")]
public class Universe {
    [XmlElement(ElementName="planet")]
    public List<Planet> Planet { get; set; }
    [XmlAttribute(AttributeName="id")]
    public string Id { get; set; }
    [XmlAttribute(AttributeName="name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName="parentId")]
    public string ParentId { get; set; }
}

我将你的XML存储在一个文件中并反序列化为一个名为dezerializedXMLSingle的对象......实际上非常酷,因为如果你在dezerializedXMLSingle行之后的代码中设置了一个断点,那么鼠标悬停并检查数据&#39; dezerializedXMLSingle&#39;的结构对象,你会看到每个行星,然后看到与这些行星相关的行星,在fila7866的情况下你会看到3个[sub]行星......希望有帮助....