过滤 XML 文档部分的有效方法
我正在寻找一种有效的方法来过滤 XML 文档。我正在使用 C#/.NET。假设我有以下原始文档:
<Bookstores>
<Bookstore>
<StoreName>Store 1</StoreName>
<Books>
<Book>
<Author>Bob</Author>
<Title>ABC</Title>
</Book>
<Book>
<Author>John</Author>
<Title>XYZ</Title>
</Book>
</Books>
</Bookstore>
</Bookstores>
我有另一个部分文档存储在其他地方:
<Book>
<Author>John</Author>
<Title>XYZ</Title>
</Book>
使用这两个文档,我需要输出第二个部分 XML 文档,包括其原始祖先。
<Bookstores>
<Bookstore>
<StoreName>Store 1</StoreName>
<Books>
<Book>
<Author>John</Author>
<Title>XYZ</Title>
</Book>
</Books>
</Bookstore>
</Bookstores>
我也愿意接受其他方式来做到这一点。我有一份原始文档,无法直接操作。我需要单独存储对该文档部分的“引用”。然后我需要使用“参考”来过滤/翻译原始文档以用于显示目的。
I am looking for an efficient way to filter an XML document. I am using C#/.NET. Say that I have the following original document:
<Bookstores>
<Bookstore>
<StoreName>Store 1</StoreName>
<Books>
<Book>
<Author>Bob</Author>
<Title>ABC</Title>
</Book>
<Book>
<Author>John</Author>
<Title>XYZ</Title>
</Book>
</Books>
</Bookstore>
</Bookstores>
I have another partial document stored somewhere else:
<Book>
<Author>John</Author>
<Title>XYZ</Title>
</Book>
Using these two documents, I need to output the second partial XML document including its original ancestors.
<Bookstores>
<Bookstore>
<StoreName>Store 1</StoreName>
<Books>
<Book>
<Author>John</Author>
<Title>XYZ</Title>
</Book>
</Books>
</Bookstore>
</Bookstores>
I am also open to other ways I might be able to do this. I have an original document that I cannot manipulate directly. I need to store a "reference" to part(s) of that document separately. And then I need to filter/translate the original document using the "reference" for display purposes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此 XSLT 转换:
应用于提供的 XML 文档时:
产生所需的正确结果:
请注意:
身份规则用于“按原样”复制任何节点,但与相同
Book
元素不匹配的Book
元素除外参考文档中的内容。匹配
Book
的模板决定复制当前节点(通过对其应用身份规则)仅当两个子节点(Author
code> 和
Title
) 与参考文档中的某些Book
元素的子元素具有相同的值。为了方便起见,我已将参考文档嵌入到 XSLT 样式表中。实际上,它将位于自己的 XML 文件中,只需稍微更改
$vReference
变量的定义即可。This XSLT transformation:
when applied on the provided XML document:
produces the wanted, correct result:
Do note:
The identity rule is used to copy any node "as-is", except for
Book
elements that do not match identicalBook
elements in the reference document.The template matching
Book
decides to copy the current node (by applying the identity rule on it) only if both children (Author
andTitle
) have the same value as the children of someBook
element from the reference document.Just for convenience I have embedded the reference document into the XSLT stylesheet. In practice it will be in its own XML file and this would only need a slight change in the definition of the
$vReference
variable.请尝试 LINQ to XML,
http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx。
我希望这会有所帮助。
Do try LINQ to XML,
http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx.
I hope this will help.