【问题标题】:Xml parse object inside of list of objects inside object using LINQXml使用LINQ解析对象内部对象列表中的对象
【发布时间】:2019-02-13 05:42:33
【问题描述】:

XML 文件

<Lines>
    <LineEntity>
      <Id>33947</Id>
      <Name>SEC_137438957044</Name>
      <IsUnderground>true</IsUnderground>
      <R>0.209</R>
      <ConductorMaterial>Steel</ConductorMaterial>
      <LineType>Cable</LineType>
      <ThermalConstantHeat>2400</ThermalConstantHeat>
      <FirstEnd>41990</FirstEnd>
      <SecondEnd>41992</SecondEnd>
      <Vertices>
        <Point>
          <X>407566.68007470988</X>
          <Y>5013899.3558040857</Y>
        </Point>
        <Point>
          <X>407625.00589398207</X>
          <Y>5013876.8697334668</Y>
        </Point>
        <Point>
          <X>407717.51971015992</X>
          <Y>5014160.9525629422</Y>
        </Point>
        <Point>
          <X>407559.40091708023</X>
          <Y>5014220.4665799234</Y>
        </Point>
      </Vertices>
    </LineEntity>
</Lines>

我想获得这个带有积分的Vertices 对象,但我不知道如何获得它。到目前为止我尝试了什么:

var lines = xdoc.Descendants("LineEntity")
                 .Select(line => new Line
    {
        Id = (double)line.Element("Id"),
        Name = (string)line.Element("Name"),
        ConductorMaterial = (string)line.Element("ConductorMaterial"),
        IsUnderground = (bool)line.Element("IsUnderground"),
        R = (decimal)line.Element("R"),
        FirstEnd = (int)line.Element("FirstEnd"),
        SecondEnd = (int)line.Element("SecondEnd"),
        LineType = (string)line.Element("LineType"),
        ThermalConstantHeat = (int)line.Element("ThermalConstantHeat"),
        Vertices = line.Descendants("Vertices").Select(p => new Point {
        X = (decimal)p. //can't access Element
    })
}).ToList();

【问题讨论】:

  • 您需要获取后代点(不是顶点)。 List Vertices = line.Descendants("Point").Select(p => new Point((decimal)p.Element("X"),(decimal)p.Element("Y"))).ToList ()

标签: c# xml linq parsing


【解决方案1】:

这是代码:

 ThermalConstantHeat = (int)line.Element("ThermalConstantHeat"),
 Vertices = line.Element("Vertices").Descendants("Point").Select(p => new TokenController.Point
 {
     X = (decimal)p.Element("X"),
     Y = (decimal)p.Element("Y")//can't access Element
 }).ToList()

您必须先找到 Element("Vertices"),然后才能找到 Descendants("Point") 列表

【讨论】:

  • 你不需要找到顶点来获取点。
【解决方案2】:

您需要在Elements of Vertices 中选择Elements of Point 喜欢

var lines = xdoc.Descendants("LineEntity")
    .Select(line => new Line
    {
        //Your rest of code same here

        Vertices = line.Elements("Vertices").Elements("Point").Select(p => new Point 
        {
            X = (decimal)p.Element("X"),
            Y = (decimal)p.Element("Y"),
        }).ToList()
    }).ToList();

输出:(来自调试器)

【讨论】:

    猜你喜欢
    • 2018-02-14
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多