首页 > 解决方案 > 具有相同元素的 XML 文件

问题描述

在阅读现有 XML 文档方面,我有一个小问题(对我来说这是一个大问题)。我有一个包含许多始终相同元素的文件。我需要创建一个列表,清楚地表明哪个孩子属于哪个父母。

<?xml version="1.0" encoding="utf-16"?>
<componentTree name="Location">
  <componentRef ref="47350">
    <componentRef ref="47379">
      <componentRef ref="47425">
        <componentRef ref="47471" />
        <componentRef ref="47494" />
        <componentRef ref="47517">
          <componentRef ref="47632" />
          <componentRef ref="47655" />
          <componentRef ref="47678" />
        </componentRef>
      </componentRef>
    </componentRef>
    <componentRef ref="47402">
      <componentRef ref="47448">
        <componentRef ref="47540">
          <componentRef ref="47563">
            <componentRef ref="47586" />
            <componentRef ref="47609" />
          </componentRef>
        </componentRef>
      </componentRef>
    </componentRef>
  </componentRef>
</componentTree>

例如 47517 组件 47517 父级:47425 有子级:是

有人给我小费吗?

非常感谢...

标签: c#xmllinq

解决方案


你可以在 Linq to SQl 中使用类似的东西

 XElement doc = XElement.Parse(xml);
            var result = (from item in doc.Descendants("componentRef")
                         select new {Ref = (string)item.Attribute("ref"),  Parent = (string)item.Parent.Attribute("ref"), HasChild = item.FirstNode != null }).ToList();

推荐阅读