我想从以下xml字符串中删除xmlns属性.我编写了一个

java程序,但不确定它是否需要在这里完成.

如何删除xmlns属性并获取修改后的xml字符串?

输入XML字符串:

abc

预期的XML输出字符串:

abc

Java类:

public class XPathUtils {

public static void main(String[] args) {

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>abc";

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 "";

}

}

输出:

before xml = <?xml version="1.0" encoding="UTF-8"?>abc

afterNsRemoval = [#document: null]

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐