使用XML DOM添加名称空间前缀XML String

我想使用XML DOM为XML String中的所有元素添加名称空间前缀。 例如我的字符串以这种方式出现:

 test string   test string test string   test string test string   test string test string    

我想要一个输出XML:

  test string   test string test string   test string test string   test string test string    

如何在Java中实现最佳效果?

我们可以用Transformer + SAX来做到这一点。 尝试这个:

  import java.io.StringWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; import org.xml.sax.helpers.XMLReaderFactory; public class Test { public static void main(String args[]) throws Exception { XMLReader xmlReader = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) { String namespace = "http://www.tibco.com/schemas/BWStatistics-hawk/Schema.xsd2"; String pref = "ns0:"; @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(namespace, localName, pref + qName, atts); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(namespace, localName, pref + qName); } }; TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); StringWriter s = new StringWriter(); t.transform(new SAXSource(xmlReader, new InputSource("test.xml")), new StreamResult(s)); System.out.println(s); } }