次のxml文字列からxmlns
属性を削除します。私はjava
プログラムを書いていますが、ここで何が行われる必要があるかどうかはわかりません。xmlとjavaのルート要素からxmlns属性を削除するには
xmlns
属性を削除して修正したxml文字列を取得するにはどうすればよいですか?
入力XML文字列:
<?xml version="1.0" encoding="UTF-8"?>
<Payment xmlns="http://api.com/schema/store/1.0">
<Store>abc</Store>
</Payment>
予想されるXML出力文字列:
<?xml version="1.0" encoding="UTF-8"?>
<Payment>
<Store>abc</Store>
</Payment>
Javaクラス:
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 "";
}
}
出力:
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]
... –
私はそれを試してみるよりも幸せになります。どのようにこれを実装することができますか? – user2325154
gimme数分... xpathの美しさは、選択したすべての属性を効果的に削除することができるということです。非常に複雑な文書の場合でも... xpathは "// @ *"以上です –