[英]Whats the best way to remove same tags from an xml string?
In my android app, I am getting following xml string from host: 在我的Android应用程序中,我从主机获取以下xml字符串:
<response>
<objects>
<object>
<id>1</id>
<name>Black</name>
<desc>Black color</desc>
</object>
<object>
<id>2</id>
<name>White</name>
<desc>White color</desc>
</object>
...
...
<object>
<id>99</id>
<name>Green</name>
<desc>Green color</desc>
</object>
</objects>
</response>
Its a string and i want to remove all desc tags from string. 它是一个字符串,我想从字符串中删除所有desc标签。 What is the best and easiest way to do that? 最好和最简单的方法是什么? Thanks in advance. 提前致谢。
"Best and easiest" is an opinion question. “最好,最简单”是一个意见问题。
It'd be pretty straightforward to modify one of the many examples of using the JAXP APIs to parse this document, find and discard those tags (and, presumably, their content), and output the modified document. 修改使用JAXP API解析此文档,查找并丢弃这些标记(以及可能是其内容)并输出修改后的文档的众多示例中的一个非常简单。
It'd also be pretty straightforward to write an XSLT stylesheet that did this. 编写一个执行此操作的XSLT样式表也非常简单。 Start with the "identity transform", then add 从“身份变换”开始,然后添加
<xsl:template match="desc"/>
... in other words, when you reach a <desc>
element, do nothing rather than copying it to the output. ...换句话说,当你到达<desc>
元素时,什么也不做,而不是将它复制到输出。
And in this particular case, the "Desperate Perl Hacker" approach would work -- that is, you could simply process this as a text file and discard/delete lines containing . 在这种特殊情况下,“绝望的Perl黑客”方法可行 - 也就是说,您可以简单地将其作为文本文件处理并丢弃/删除包含的行。
I think this will work. 我认为这会奏效。
String modifiedXmlString = xmlString.replaceAll("(?s)<desc>.*?</desc>","");
This use regular expression to remove the xml tag you want. 这使用正则表达式来删除所需的xml标记。 You can read more about regular expression here http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html 你可以在http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html上阅读有关正则表达式的更多信息。
Presumably you have your XML parsed as a document? 想必你将XML解析为文档? You could get all the nodes using, lets say XPath, then call getParentNode().removeChild(node)
on each node. 您可以使用所有节点,比如XPath,然后在每个节点上调用getParentNode().removeChild(node)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.