JAVA为xml的所有元素添加前缀

时间:2013-04-22 13:54:33

标签: java xml namespaces

有什么方法可以在java中为我的xml的每个元素添加前缀?例如,我有以下xml:

    <node1 xmlns="www.test.com">
       <node2>abc</node2>
       <node3>
           <node3_1>test1</node3_1>
       </node3>
     </node1>

我想将其转换为:

    <test:node1 xmlns test="www.test.com">
       <test:node2>abc</test:node2>
       <test:node3>
           <test:node3_1>test1</test:node3_1>
       </test:node3>
     </test:node1>

有一种简单的方法吗?到目前为止,我已经尝试过:

 String messageString = message.getPayloadAsString();
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
 DocumentBuilder builder;  
 Document document = null;
 try  
    {  
        builder = factory.newDocumentBuilder();  
        document = builder.parse( new InputSource( new StringReader( messageString) ) );  
    } catch (Exception e) {  
        e.printStackTrace();  
    } 

    XmlObject inboundMessageObject = XmlObject.Factory.parse(document);
    XmlOptions xmlOptions = new XmlOptions(); 
    Map<String, String> namespaceMap = new HashMap<String, String>(); 
    namespaceMap.put("www.test.com", "test");
    xmlOptions.setSaveSuggestedPrefixes(namespaceMap);

            xmlObject.save(System.out, xmlOptions); 

    String prefixedXML = inboundMessageObject.xmlText(xmlOptions);
    return prefixedXML;

我看到的是,prefixedXML String与messageString字符串相同。

1 个答案:

答案 0 :(得分:0)

xml = xml.replaceFirst("xmlns=", "xmlns:test=").replaceAll("<(/?)", "<$1test:");