如何使用Java替换xml标记中的所有冒号?

时间:2014-10-07 06:57:30

标签: java

我想在所有标记值中替换冒号(:)。但是我的xml有名称空间后缀。如何使用Java安全地替换它?

e.g。

<ns:shop>ABC : Adress 1</ns:shop>
   <ns:person>John : Lee</ns:person>
<ns:shop>DEF: Adress 2</ns:shop>
   <ns:person>Susan: Lee</ns:person>

我想要这样的结果:

<ns:shop>ABC Adress 1</ns:shop>
   <ns:person>John Lee</ns:person>
<ns:shop>DEF: Adress 2</ns:shop>
   <ns:person>Susan Lee</ns:person>

1 个答案:

答案 0 :(得分:0)

您是否尝试过更换下面的特定标签?

public class replacetagcontent {
    static String inputFile = "C:/temp/shop.xml";
    static String outputFile = "C:/temp/shop_modified.xml";    

    public static void main(String[] args) throws Exception {         
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
        Document doc = builder.parse(inputFile);        

        // locate the node(s)
        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new MyNamespaceContext());
        NodeList shp_nodes = (NodeList)xpath.evaluate("//ns:shop", doc, XPathConstants.NODESET);
        NodeList pers_nodes = (NodeList)xpath.evaluate("//ns:person", doc, XPathConstants.NODESET);

        // make the change
        for (int i = 0; i < shp_nodes.getLength(); i++) {
            String name_value = shp_nodes.item(i).getTextContent();
            shp_nodes.item(i).setTextContent(name_value.replace(":",""));
            String title_value = pers_nodes.item(i).getTextContent();
            pers_nodes.item(i).setTextContent(title_value.replace(":",""));
        }

        // save the result
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
    }

    private static class MyNamespaceContext implements NamespaceContext {
        public String getNamespaceURI(String prefix) {
            if("ns".equals(prefix)) {
                return "http://www.example.org/schema";
            }
            return null;
        }
        public String getPrefix(String namespaceURI) {
            return null;
        }
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    } 
}