Search code examples
javaxmlprefix

How can i replace attribute of prefix in xml?


I want to replace an attribute of xml in java.

How can i replace that?

Please help me.

xml is like this:

<header p1:name="blabla">
<body>
<description>hello world !!!</description>
</body>
</header>
<!-- TO-BE -->
<header name="blabla">
<body>
<description>hello world !!!</description>
</body>
</header>

I want to replace 'p1:' to space area like TO-BE.


Solution

  • When you want to transform XML from Java, I would suggest using XSLT. For simple tasks you can use the XSLT 1.0 processor that comes with the JDK; for more complex tasks you can download an XSLT 3.0 implementation such as Saxon.

    However, XSLT assumes that the XML input is well-formed. The sample you have shown isn't, because it uses a namespace prefix p1 that hasn't been declared. This suggests a problem further up the processing pipeline, and rather than getting rid of this prefix, you should perhaps consider how it got there in the first place: errors that create bad data should be fixed at source, rather than repairing the data later.