【问题标题】:How should I organize two objects in order to be able to join them on a key?我应该如何组织两个对象以便能够将它们连接到一个键上?
【发布时间】:2013-02-20 17:42:42
【问题描述】:

所以基本上,我正在阅读两个 XML 文档。第一个有两个需要存储的值:名称和值。第二个有四个值:Name、DefaultValue、Type 和 Limit。在阅读文档时,我想将每个存储到某个对象中。然后,我需要能够将这两个对象组合成一个对象,其中存储了 5 个值。 XML 文档的长度不同,但第二个文档的大小始终至少是第一个文档的大小。

示例:

<XML1>
  <Item1>
    <Name>Cust_No</Name>
    <Value>10001</Value>
  </Item1>
  <Item4>
    ITEM4 NAME AND VALUE
  </Item4>
  <Item7>
    ITEM 7 NAME AND VALUE
  </Item7>
</XML1>

<XML2>
  <Item1>
    <Name>Cust_No</Name>
    <DefaultValue></DefaultValue>
    <Type>varchar</Type>
    <Limit>15</Limit>
  </Item1>
  6 MORE TIMES ITEMS 2-7
</XML2>

我已经有代码循环通过 XML。我真的只需要思考什么是存储数据的最佳方式而已。最终,我希望能够在 Name Key 上加入这两个对象。我尝试了string[]arrayList[],但我在组合它们时遇到了困难。我还阅读了Dictionary,但也无法实现(我之前从未使用过Dictionary)。

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    这是 Linq to Xml 查询,它将连接两个 XDocument 并为连接的项目选择匿名对象。每个对象都有五个属性:

    var query = 
      from i1 in xdoc1.Root.Elements()
      join i2 in xdoc2.Root.Elements()
          on (string)i1.Element("Name") equals (string)i2.Element("Name") into g
      let j = g.SingleOrDefault() // get joined element from second file, if any
      select new {
          Name = g.Key,
          Value = (int)i1.Element("Value"),
          DefaultValue = (j == null) ? null : (string)j.Element("DefaultValue"),
          Type = (j == null) ? null : (string)j.Element("Type"),
          Limit = (j == null) ? null : (string)j.Element("Limit")
      };
    

    这样创建的 XDocuments:

    var xdoc1 = XDocument.Load(path_to_xml1);
    var xdoc2 = XDocument.Load(path_to_xml2);
    

    查询的用法:

    foreach(var item in query)
    {
       // use string item.Name
       // integer item.Value
       // string item.DefaultValue
       // string item.Type
       // string item.Limit
    }
    

    【讨论】:

    • 谢谢!这很棒。但是我现在如何访问数据?它存储在什么地方?
    猜你喜欢
    • 2022-11-22
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2014-10-06
    • 1970-01-01
    • 2020-08-22
    相关资源
    最近更新 更多