1

有什么办法可以在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 字符串与 messageString 字符串相同。

4

1 回答 1

0

尝试

xml = xml.replaceFirst("xmlns=", "xmlns:test=").replaceAll("<(/?)", "<$1test:");
于 2013-04-22T14:04:00.277 回答