【问题标题】:Linq to XML, getting items in proper tree structureLinq to XML,以正确的树结构获取项目
【发布时间】:2011-06-14 21:59:13
【问题描述】:

我有一些这样的 XML

<case>
<tab tabdescription="text here">
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />  
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />  
</tab>

<tab tabdescription="text here">
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />  
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />  
</tab>

<tab tabdescription="text here">
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />  
    <subtab subtab_description="subtab description here" subttab_text="subtab text here" />  
</tab>

<exhibit exhibitdescription="exhibit description here">
    <exhibitfilename>FileName.File</exhibitfilename />
</exhibit>

<exhibit exhibitdescription="exhibit description here">
    <exhibitfilename>FileName.File</exhibitfilename />
</exhibit>`  

<exhibit exhibitdescription="exhibit description here">
    <exhibitfilename>FileName.File</exhibitfilename />
</exhibit>
</case>

在我的 c# 代码中,我有一个包含 tabdescription 属性和 List&lt;subtab&gt; 对象的选项卡对象,并且 subtab 对象包含一个 subtabdescription 属性和一个 subtabtext 属性。我还有一个带有展览描述和展览文件名属性的展览对象。

我需要填充这些对象,以便完成后我将拥有三个选项卡对象,每个选项卡对象都包含它们的 3 个子选项卡对象,并填充了所有适当的字段。我还需要 3 个展览对象,其中填充了展览描述和展览文件名。

我以前用 ling to xml 做过一些工作,但我从来不用担心以 xml 的完美树形表示形式取出对象,因为通常它们有 id,我可以在事后浏览列表并将项目正确分组。对此的任何帮助都会很棒。

【问题讨论】:

    标签: linq-to-xml


    【解决方案1】:

    如果您不熟悉 LINQ to XML,您可以考虑使用 XmlSerializer 将 XML 反序列化为您的对象,只需添加一些属性即可。 或者使用 LINQ to XML,例如

    XDocument doc = XDocument.Load("case.xml");
    IEnumerable<Tab> tabs =
      from tab in doc.Root.Elements("tab")
      select new Tab() {
        Description = (string)tab.Attribute("tabdescription"),
        Subtabs = (from subtab in tab.Elements("subtab")
                   select new Subtab() {
                     Subtabdescription = (string)subtab.Attribute("subtabdescription"),
                     Subtabtext = (string).subtab.Attribute("subtabtext")
                   }).ToList()
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多