如何使用 XPath 查询在 xml 节点中添加字符串内容(空节点/附加到现有内容)
我已经有以下 xml 结构,其子节点为 title、desc、symp、diag、treat addinfo 等。我想检查 addinfo 是否包含任何内容,并向其附加一些字符串,例如“这是附加信息”。有很多疾病标题我需要根据疾病标题-标题标签来检查addifo标签。
<chapter>
<disease type="Name">
<title>Name</title>
<desc>--------------</desc>
<symp>--------------</symptoms>
<diag>-------------</diagnosis>
<treat>-------------</treatment>
<addinfo></addinfo>
</disease>
</chapter
>
我正在使用 XPath 查询根据疾病名称搜索标签的内容。 谢谢
I have the following xml structure already available with the childnodes as title, desc, symp, diag, treat addinfo etc. I want to check that whether addinfo contains any thing and also append some string to it like "This is additional info". There are many disease title I need to check the addifo tag according to disease title-title tag.
<chapter>
<disease type="Name">
<title>Name</title>
<desc>--------------</desc>
<symp>--------------</symptoms>
<diag>-------------</diagnosis>
<treat>-------------</treatment>
<addinfo></addinfo>
</disease>
</chapter
>
I am using XPath query for searching the content of the tags according to the disease name.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
XPath 只能从文档中检索信息,而不能修改它。
XQuery 可以生成文档的修改副本,但这并不是特别容易,因为您需要显式复制所有不想更改的部分。
XSLT 是生成文档修改副本的更好选择;或 XQuery 更新工具(如果您愿意)。
XPath can only retrieve information from your document, it cannot modify it.
XQuery can produce a modified copy of your document, but it's not particularly easy, because you need to explicitly copy all the parts that you don't want to change.
XSLT is a better bet for producing a modified copy of the document; or XQuery Update Facility if you prefer.
您可以使用这样的 XPath 来查看 addinfo 是否为空:
//addinfo[not(node())]
更新:
好的,现在完全不知道您想要什么。这听起来是一个非常简单的问题。您将创建某种
getText()
方法,该方法给定 XML 节点,获取与其关联的文本(如果有的话,或者返回 null 或空字符串)。然后,您将遍历所有疾病,并针对每种疾病执行您的逻辑:if( string.isNullOrEmpty(getText(disease, "addinfo")) ) { // do some }
--如果你想检查 addinfo 是否为空或向其中添加内容等。You can use an XPath like this to see if addinfo is empty or not:
//addinfo[not(node())]
UPDATE:
Ok, now am totally lost as to what you want. It sounds like a really straightforward problem. You would create some sort of
getText()
method that given an XML node, gets the text associated with it (if any or returns null or empty string). Then you would do a traversal of all the diseases and for each disease, perform your logic:if( string.isNullOrEmpty(getText(disease, "addinfo")) ) { // do something }
-- if you want to check whether addinfo is empty or add stuff to it etc..