简体   繁体   English

Java XML解析-删除第一个标签

[英]Java XML Parse - Remove First Tag

I would like to delete a few Tags from my XML string. 我想从我的XML字符串中删除一些标签。 It sounds simple, and I'm sure it its, but I'm having problems deleting the main Tag and keeping the SubTags inside. 听起来很简单,而且我敢肯定,但是我在删除主标签并将子标签保留在内部时遇到了问题。

Here is an example: 这是一个例子:

<Tag1 version = "">
    <SubTag1>
    </SubTag1>
    <SubTag2>
    </SubTag2>
</Tag1>

I would like to keep only the "SubTag2" and everything inside it. 我只想保留“ SubTag2”及其内部的所有内容。

Which is the best way to approach this? 哪个是解决此问题的最佳方法?

I tried using REGEX to delete SubTag1, but I found here that this is never a good solution in XML: 我尝试使用REGEX删除SubTag1,但是在这里我发现这永远不是XML的好解决方案:

result = result.replaceAll("<SubTag1>[\\s\\S]*?</SubTag1>","");

Thank you in advance. 先感谢您。

You could use JSoup ( https://jsoup.org/ ) or another library to parse your string. 您可以使用JSoup( https://jsoup.org/ )或其他库来解析您的字符串。 Then you can access the DOM tree and extract only the part with the specific tag. 然后,您可以访问DOM树并仅提取具有特定标签的零件。

It would look like this: 它看起来像这样:

String xml = "<Tag1 version = \"\"><SubTag1></SubTag1><SubTag2></SubTag2></Tag1>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Elements subTag2 = doc.getElementsByTag("SubTag2");

If there is only one element with the tag "SubTag2" you can get access to it like this: 如果只有一个带有标签“ SubTag2”的元素,则可以像下面这样访问它:

subTag2.get(0);

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

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