C#如何解析XML文件

时间:2015-01-15 08:24:18

标签: c# linq xml-parsing

我在使用以下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>

我需要选择:

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;

2 个答案:

答案 0 :(得分:2)

试试这个: -

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()
           });

我得到以下输出: -

enter image description here

答案 1 :(得分:1)

        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

的位置添加其他检查