帮助合并 XML 数据
我有两个 XMLDocument,其中包含一些相似的信息,但还有其他节点包含两者之间的不同信息。
我正在使用 XMLSerialization 将数据放入如图所示的结构 此处
我知道您可以使用数据集合并 XML 文件,如下所示 here 但我想以某种方式将我看到的第一个文档序列化到我的类中,然后将第二个文档附加到我的类结构中。
有什么想法如何做到这一点或者有更好的方法吗?在信息相似的第二个文档上,我很乐意用第二个文档数据覆盖它,例如每个文档都有一个日期,因此我的日期属性可以是第二个文档的日期属性。
这是数据
<ROOT>
<ID>2</ID>
<PART>4a</PART>
<NAME>JEFF</NAME>
<ADDRESS>
<ST>10001</ST>
<ID>123456789</ID>
</ADDRESS>
<PARTNUMBER>001</PARTNUMBER>
<DATE>2009 -06-05T16.18.05</DATE>
</ROOT>
<ROOT>
<ID>2</ID>
<PART>4b</PART>
<NAME>JEFF</NAME>
<RELATIVE>
<ST>10001</ST>
<ID>1234567890QWERTYUIOP</ID>
</RELATIVE>
<PARTNUMBER>002</PARTNUMBER>
<DATE>2009 -06-05T16.17.41</DATE>
</ROOT>
I have two XMLDocuments that contain some similar information but there are other nodes that contain different information between the two.
I am using XMLSerialization to put my data into a structure as shown here
I know you can merge XML files by using a DataSet as shown here but I want to somehow serialize the first document I see into my class and then append the second document to my class structure.
Any ideas how to do that or is there a better approach? On the second document where the information is similar I am happy to overwrite it with the second document data for example each document has a DATE so my Date property can be that of the second document.
Here is the data
<ROOT>
<ID>2</ID>
<PART>4a</PART>
<NAME>JEFF</NAME>
<ADDRESS>
<ST>10001</ST>
<ID>123456789</ID>
</ADDRESS>
<PARTNUMBER>001</PARTNUMBER>
<DATE>2009 -06-05T16.18.05</DATE>
</ROOT>
<ROOT>
<ID>2</ID>
<PART>4b</PART>
<NAME>JEFF</NAME>
<RELATIVE>
<ST>10001</ST>
<ID>1234567890QWERTYUIOP</ID>
</RELATIVE>
<PARTNUMBER>002</PARTNUMBER>
<DATE>2009 -06-05T16.17.41</DATE>
</ROOT>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
You can do something like that :
托马斯的回答真的很棒。然而,尽管它在给定的 XML 上运行得非常好,但我发现它在带有属性的 XML 上遇到了一些问题(尽管代码理论上确实可以处理它)。
然而,尝试从 XAttribute 转换为 XNode 时,这一行会抛出 InvalidCastException:
尽管如此,我发现以下更改对我有用。而不是
尝试这个:
似乎对我有用,尽管我不是这些问题的专家。这仅供其他遇到此问题的人参考。
编辑:此外,请注意
doc.Dump()
对我来说不存在,并且在编译时会中断。我正在使用.NET 3.5;也许汤姆的答案取决于不同的版本(3.0?),这也可能解释我收到的错误消息?Thomas' answer is really great. However although it worked perfectly well on the given XML, I found it had some trouble on XML with attributes (although the code does theoretically deal with it).
However this line would throw an InvalidCastException trying to convert from XAttribute to XNode:
Nonetheless I found that the following changes worked for me. Instead of
Try this:
Seems to work for me, though I'm no expert on these matters. This is just an FYI for anyone else who comes across this.
EDIT: In addition, note that
doc.Dump()
doesn't exist for me and breaks when compiling. I'm using .NET 3.5; perhaps Tom's answer depended on a different version (3.0?), and that might also account for the error messages I got?