[英]How can I replace all colons in xml tag use Java?
我想在所有標記值中替換冒號(:)。 但是我的xml有名稱空間后綴。 如何使用Java安全地替換它?
例如
<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>
您是否嘗試過替換下面的特定標簽?
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.