C# 如何解析 XML 文件

C# How to parse XML File

我在处理以下 XML 文件时遇到问题:

 <?xml version="1.0" encoding="UTF-16" ?> 
 <Export>
  ...
  <PID No="5" OffsetY="5" OffsetX="16.25" TRef="-127471" />
  ...
  <PID No="5" OffsetY="12" OffsetX="42" TRef="-127476" />
  <PID No="5" OffsetY="10" OffsetX="63" TRef="-127477" />
  ...
  <Folder FolderType="1025">
   <CFolder DisplayName="DName">
    <Object OID="-127471" ObjectName="5" ObjectType="25" /> 
    ...
    <Object OID="-127476" ObjectName="6" ObjectType="25" /> 
    <Object OID="-127477" ObjectName="7" ObjectType="25" />
    ...
   </CFolder>
  </Folder>
  ... 

 </Export>

我需要 select:

OffsetX OffsetY ObjectName
 16.25     5          5
 ...
 42        12         6
 63        10         7
 ...

其中 TRef=OID

有人可以帮助我吗? 我只得到第一行。这段代码是我设法做到的一切:

XDocument doc = XDocument.Load(FileName);
XElement pid = doc.Root.Element("PID");
IEnumerable<XAttribute> OffsXlist =
            from offX in pid.Attributes("OffsetX")
            select offX;
IEnumerable<XAttribute> OffsYlist =
            from offY in pid.Attributes("OffsetY")
            select offY;

试试这个:-

var result = xdcoc.Descendants("PID")
          .Select(x => new
          {
              OffetX = (string)x.Attribute("OffsetX"),
              OffsetY = (string)x.Attribute("OffsetY"),
              ObjectName = x.Parent.Descendants("Object")
                           .Where(z => z.Attribute("OID").Value == 
                                                      x.Attribute("TRef").Value)
                            .Select(z => (string)z.Attribute("ObjectName"))
                            .FirstOrDefault()
           });

我得到以下输出:-

        var xDocument = XDocument.Load(FileName);

        var pidNodes = xDocument.Descendants("PID");
        var pids = pidNodes.Select(x => new
        {
            OffsetX = x.Attribute("OffsetX").Value,
            OffsetY = x.Attribute("OffsetY").Value,
            TRef = x.Attribute("TRef").Value
        });

        var objectNodes = xDocument.Descendants("Object");
        var objects = objectNodes.Select(x => new
        {
            OID = x.Attribute("OID").Value,
            ObjectName = x.Attribute("ObjectName").Value,
            ObjectType = x.Attribute("ObjectType").Value
        });

        var result = pids.Select(x => new
        {
            OffsetX = x.OffsetX,
            OffsetY = x.OffsetY,
            ObjectName = objects.Single(o => o.OID == x.TRef).ObjectName
        });

我假设给定的 TRef 总是有一个对应的 OID。如果不是这种情况,则必须在我放置 objects.Single(o => o.OID == x.TRef).ObjectName

的位置添加额外的检查