如何使用java代码删除Xml中的属性值?

时间:2022-03-09 08:54:42

I am working with an xml file and I want to delete a portion of an attribute value, but not the whole attribute.

我正在处理一个xml文件,我想删除属性值的一部分,而不是整个属性。

For example:

例如:

<parent>
<variable dim = "dimension1 dimension2" value = " variableValue"/>
</parent>

I want to delete only ' dimension2 ' from the 'dim' attribute.

我只想从“dim”属性中删除“dimension2”。

How can I do that.?

我怎么做呢?

1 个解决方案

#1


0  

It depends on which library you use to parse XML with. I personally like JDOM because its much more straight forward for working with XML. If you were to do that it would be:

这取决于使用哪个库解析XML。我个人喜欢JDOM,因为它更直接地处理XML。如果你这样做的话,它将是:

Element element = ...;
Attribute attribute = element.getAttribute("dim");
attribute.setValue( attribute.getValue().replace("dimension2", "") );

It'd be very similar with other XML processes.

它与其他XML进程非常相似。

http://www.jdom.org/

http://www.jdom.org/

If you are parsing with SAX it's more complicated because you have to process the whole document, and modify it while you are parsing it with SAX. You probably are just using DOM, but just to cover most cases. If you're using a pull parser it's roughly the same as DOM.

如果使用SAX进行解析,则会更加复杂,因为您必须处理整个文档,并在使用SAX解析文档时对其进行修改。您可能只是在使用DOM,但只是为了涵盖大多数情况。如果使用拉解析器,它与DOM大致相同。

#1


0  

It depends on which library you use to parse XML with. I personally like JDOM because its much more straight forward for working with XML. If you were to do that it would be:

这取决于使用哪个库解析XML。我个人喜欢JDOM,因为它更直接地处理XML。如果你这样做的话,它将是:

Element element = ...;
Attribute attribute = element.getAttribute("dim");
attribute.setValue( attribute.getValue().replace("dimension2", "") );

It'd be very similar with other XML processes.

它与其他XML进程非常相似。

http://www.jdom.org/

http://www.jdom.org/

If you are parsing with SAX it's more complicated because you have to process the whole document, and modify it while you are parsing it with SAX. You probably are just using DOM, but just to cover most cases. If you're using a pull parser it's roughly the same as DOM.

如果使用SAX进行解析,则会更加复杂,因为您必须处理整个文档,并在使用SAX解析文档时对其进行修改。您可能只是在使用DOM,但只是为了涵盖大多数情况。如果使用拉解析器,它与DOM大致相同。