【问题标题】:Parsing xml. Objects with relation (one-to-many)解析xml。有关系的对象(一对多)
【发布时间】:2012-03-11 09:12:36
【问题描述】:

我有一个 xml 文件:

<?xml version='1.0' encoding='windows-1251' standalone='yes'?><XML>
  <Result>Ok</Result>
  <Error></Error>
  <Remark></Remark>
  <Data>
    <Theatres>
      <Theatre ID='1' ShowBusyPlaces='1'> // maybe more than one
        <Name><![CDATA[PlaceName]]></Name>
        <NameFull><![CDATA[PlaceName]]></NameFull>
        <Remark><![CDATA[]]></Remark>
        <Address><![CDATA[]]></Address>
        <Halls Count='3'>
          <Hall ID='1'>
            <Name><![CDATA[Redisson]]></Name>
            <Levels Count='1'> 
              <Level ID='1' Geometry='1'> // maybe more than one
                <Name><![CDATA[Radisson]]></Name>
              </Level>
            </Levels>
          </Hall>
          <Hall ID='3'>
            <Name><![CDATA[Test 2]]></Name>
            <Levels Count='0'></Levels>
          </Hall>
          <Hall ID='2'>
            <Name><![CDATA[тест]]></Name>
            <Levels Count='1'>
              <Level ID='4' Geometry='2'>
                <Name><![CDATA[ттт]]></Name>
              </Level>
            </Levels>
          </Hall>
        </Halls>
      </Theatre>
    </Theatres>
  </Data>
</XML>

而且,我有两个类:BasePlaceHallPlan(关系为一对多)

BasePlace:OID, Name, Address
HallPlan:OID, BasePlaceId, HallId, LevelId

例如上面的结果必须是:

BasePlace table:
OID     Name         Address
1      PlaceName     

HallPlan table:
OID     BasePlaceId, HallId, LevelId
1          1           1       1
2          1           2       4
3          1           3      null

此查询返回仅填充 BasePlace 对象:

var places = from element in XDocument.Parse(xml).Descendants("Theatre")
                          select new BasePlace
                                     {
                                         OIDPremiera = (int) element.Attribute("ID"),
                                         Name = (string) element.Element("Name"),
                                         Address = (string) element.Element("Address"),
                                     };

如何正确填写HallPlan(包含所有字段以及与BasePlace 的关系)? 谢谢。

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    应该是这样的:

            var plans = from element in XDocument.Parse(xml).Descendants("Hall")
                        select new HallPlan
                        {
                            OIDHallPlan = (int) element.Attribute("ID"),
                            BPRef = (BasePlace) (from BasePlace1 in places
                                    where (BasePlace1.OIDPremiera == (int)element.Parent.Parent.Attribute("ID"))
                                    select BasePlace1).FirstOrDefault(),
                            // ...
                        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2015-02-12
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      相关资源
      最近更新 更多