【问题标题】:Compare elements from two xml documents based on element value in C#根据 C# 中的元素值比较两个 xml 文档中的元素
【发布时间】:2015-08-09 03:45:35
【问题描述】:

我正在尝试加入基于相同元素的两个 XML,但我的代码没有返回任何内容。 var 结果为空。有人可以帮忙解决这个问题吗?非常感谢!

文件一:

<bookstore>
   <book>
     <bookID>100</bookID>
     <name> The cat in the hat </name>
   </book>
   <book>
    <bookID>90</bookID>
    <name> another book </name>
   </book>
   <book>
      <bookID>103</bookID>
      <name> a new book </name>
  </book>
</bookstore>

文件二

<bookstore>
  <book>
    <bookID>100</bookID>
    <content> story </content>
  </book>
  <book>
    <bookID>90</bookID>
    <content> fiction </content>
  </book>
  <book>
    <bookID>103</bookID>
    <content> bio </content>
  </book>
 </bookstore>

我正在寻找的结果是这样的:

<result>
    <bookInfo>
       <bookID>103</bookID>
       <name> a new book </name>
       <content> bio </content>
    <bookInfo>
 </result>

我当前使用的(错误)代码是:

var reslut =    
                from a in fileone.Descendants("bookstore")
                join b in filetwo.Descendants("bookstore")

            on (string)fileone.Descendants("bookID").First() equals (string)filetwo.Descendants(""bookID"").First() 
            select new XElement("bookInfo", a, b);

【问题讨论】:

  • 我也尝试比较 bookstore.Element("bookID") 但这也返回一个空文件

标签: c# xml linq join element


【解决方案1】:

您想在&lt;bookID&gt; 子值上加入&lt;book&gt; 元素,然后返回包含bookIDnamecontent 元素的&lt;bookInfo&gt; 元素:

var bookInfos =
        from a in fileone.Descendants("book")
        join b in filetwo.Descendants("book")
            on (string)a.Element("bookID") equals (string)b.Element("bookID")
        select new XElement("bookInfo", 
                                a.Element("bookID"), 
                                a.Element("name"), 
                                b.Element("content")
                            );
var result = new XElement("result", bookInfos);
Console.WriteLine(result.ToString());

Dotnetfiddle Demo

输出:

<result>
  <bookInfo>
    <bookID>100</bookID>
    <name> The cat in the hat </name>
    <content> story </content>
  </bookInfo>
  <bookInfo>
    <bookID>90</bookID>
    <name> another book </name>
    <content> fiction </content>
  </bookInfo>
  <bookInfo>
    <bookID>103</bookID>
    <name> a new book </name>
    <content> bio </content>
  </bookInfo>
</result>

【讨论】:

  • 感谢您的回答!但是,如果我想将其余项目值保留在 fileone 中,而不指定元素“内容”,该怎么办?我的意思是 fileone 中可能还有其他元素,例如 ...etc
  • 你可以说:select new XElement("bookInfo", a.Element("name"), b.Elements())。这将只取第一个 XML 中的 name 元素,以及第二个 XML 中的所有元素(bookID、内容等)
猜你喜欢
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
  • 2019-12-07
相关资源
最近更新 更多