简体   繁体   English

如何使用 libxml2 过滤掉节点

[英]How to filter out nodes using libxml2

Given an XML document and an XPath expression, I want to create a new document which has all of the nodes of the original document with the exception of the nodes selected by the XPath expression, effectively giving the result of a subtract filter.给定一个 XML 文档和一个 XPath 表达式,我想创建一个新文档,其中包含原始文档的所有节点,但由 XPath 表达式选择的节点除外,有效地给出了一个过滤器的结果。

My idea was to use the xmlXpathEvalExpression() function, and for each node in the root document tree, copy the node over unless the node matches the returned xmlNodeSet .我的想法是使用xmlXpathEvalExpression() function,并且对于根文档树中的每个节点,复制该节点,除非该节点与返回的xmlNodeSet匹配。 However, libxml2 gives no hints about how, or even if, nodes can be tested for equality.但是,libxml2 没有给出关于如何或是否可以测试节点是否相等的提示。

Are you supposed to compare the pointers to the nodes in the returned set?您是否应该比较指向返回集中节点的指针? Or are you supposed to compare the given node names/namespaces?或者你应该比较给定的节点名称/命名空间?

As mentioned in the comments, the node pointers returned from evaluating an XPath expression point directly to the nodes in the original document.如评论中所述,从评估 XPath 表达式返回的节点指针直接指向原始文档中的节点。 [1] So you can simply call xmlUnlinkNode on each node in the returned node set to remove it from the document. [1]因此,您只需在返回的节点集中的每个节点上调用xmlUnlinkNode即可将其从文档中删除。 Then, in a second step, call xmlFreeNode on each node to free the nodes.然后,在第二步中,在每个节点上调用xmlFreeNode以释放节点。 It's important to not call xmlFreeNode before all nodes are unlinked.在取消链接所有节点之前不要调用xmlFreeNode很重要。 [2] [2]

[1] Except for namespace nodes returned from the namespace axis namespace::* with type XML_NAMESPACE_DECL , but these are rarely used. [1] 除了从命名空间轴namespace::*返回的命名空间节点,类型为XML_NAMESPACE_DECL ,但这些很少使用。

[2] It should work to immediately free each node if you iterate the node set in reverse order. [2] 如果您以相反的顺序迭代节点集,它应该可以立即释放每个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM