Wie zu entfernen xmlns-Attributs aus dem root-element im xml und java

Möchte ich entfernen Sie die xmlns Attribut aus folgenden xml-string. Ich habe geschrieben eine java Programm aber nicht sicher, ob es das macht, was hier getan werden muss.

Wie Entferne ich die xmlns - Attribut und Holen Sie die geänderte xml-string ?

XML-Input-string:

<?xml version="1.0" encoding="UTF-8"?>
<Payment xmlns="http://api.com/schema/store/1.0">
    <Store>abc</Store>
</Payment>

Erwarteten XML-Ausgabe-string:

<?xml version="1.0" encoding="UTF-8"?>
<Payment>
    <Store>abc</Store>
</Payment>

Java-Klasse:

public class XPathUtils {

    public static void main(String[] args) {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"http://api.com/schema/store/1.0\"><Store>abc</Store></Payment>";
        String afterNsRemoval = removeNameSpace(xml);
        System.out.println("afterNsRemoval = " + afterNsRemoval);
    }

    public static String removeNameSpace(String xml) {
        try {
            System.out.println("before xml = " + xml);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(xml));
            Document xmlDoc = builder.parse(inputSource);
            Node root = xmlDoc.getDocumentElement();
            NodeList rootchildren = root.getChildNodes();
            Element newroot = xmlDoc.createElement(root.getNodeName());
            for (int i = 0; i < rootchildren.getLength(); i++) {
                newroot.appendChild(rootchildren.item(i).cloneNode(true));
            }
            xmlDoc.replaceChild(newroot, root);
            return xmlDoc.toString();
        } catch (Exception e) {
            System.out.println("Could not parse message as xml: " + e.getMessage());
        }
        return "";
    }
}

Ausgabe:

before xml = <?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment>

afterNsRemoval = [#document: null]
  • Ich werde mehr als glücklich sein, um es auszuprobieren. Irgendwelche Hinweise, wie kann dies umgesetzt werden?
  • gib mir ein paar Minuten... die Schönheit mit xpath ist, dass Sie können effektiv entfernen Sie alle Attribute Ihrer Wahl... auch für ein sehr Komplexes Dokument, ... der xpath wird nicht mehr als "//@*"...
InformationsquelleAutor Nital | 2016-05-20
Schreibe einen Kommentar