如何从xml和java中的根元素中删除xmlns属性
发布时间:2020-12-16 23:12:37 所属栏目:百科 来源:网络整理
导读:我想从以下xml字符串中删除xmlns属性.我编写了一个 java程序,但不确定它是否需要在这里完成. 如何删除xmlns属性并获取修改后的xml字符串? 输入XML字符串: ?xml version="1.0" encoding="UTF-8"?Payment xmlns="http://api.com/schema/store/1.0" Storeabc/
我想从以下xml字符串中删除xmlns属性.我编写了一个
java程序,但不确定它是否需要在这里完成.
如何删除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] 解决方法
这是使用XPath和vtd-xml(我是作者)的代码…
import com.ximpleware.*; import java.io.*; public class removeAttrNode { public static void main(String[] s) throws VTDException,Exception{ VTDGen vg = new VTDGen(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String xml = "<?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment>"; vg.setDoc(xml.getBytes()); vg.parse(false); // turn off namespace awareness so that VTDNav vn = vg.getNav(); AutoPilot ap = new AutoPilot(vn); XMLModifier xm = new XMLModifier(vn); ap.selectXPath("//@xmlns"); int i=0; while((i=ap.evalXPath())!=-1){ xm.remove(); } xm.output(baos); System.out.println(baos.toString()); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |