簡體   English   中英

用Java中的String替換XML文檔中的元素

[英]Replacing Elements in a XML document with String in Java

我正在編寫一個HTTP服務器,在該服務器中我將在HTTP PUT中接收XPATH,並在請求正文中接收數據。

我將需要用XML文檔中HTTP請求數據中的數據替換XPATH表達式的結果

例如

XML文檔是

<presence>
<tuple id="x8eg92n">
<note> i am reading email 3 times a day </note>
</tuple>
</presence>

HTTP請求例如

  PUT /pidf-manipulation/users/sip:someone@example.com/index/
  ~~/presence/tuple%5b@id='x8eg92n'%5d/note HTTP/1.1
  If-Match: "xyz"
  Host: xcap.example.com
  Content-Type: application/xcap-el+xml
  ...

  <note>I'm reading mails on Tuesdays and Fridays</note>

以上內容應將XML中的note元素替換為PUT請求。 客戶端可以通過這種方式發送任何XPATH並替換XML文檔的內容。

請幫助如何使用Java代碼完成此操作。

基本上,您需要做的是:

  1. 加載要更改的xml;
  2. 加載要在替換中使用的片段;
  3. 在[1]中加載的文檔中采用[2]中加載的節點;
  4. 使用XPath查找要替換的節點;
  5. 從您在[4]中找到的節點獲取父節點,從父節點中移除[4]中的節點,然后添加您采用的節點。

您可以使用類似的方法:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class XmlXPathReplace {

    public static void main(final String[] args) throws SAXException, IOException, ParserConfigurationException,
            XPathExpressionException, TransformerException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = factory.newDocumentBuilder();

        // step 1.
        Document doc = builder.parse(new ByteArrayInputStream(( //
                "<?xml version=\"1.0\"?>" + //
                        "<people>" + //
                        "<person><name>First Person Name</name></person>" + //
                        "<person><name>Second Person Name</name></person>" + //
                        "</people>" //
                ).getBytes()));

        // step 2
        String fragment = "<name>Changed Name</name>";
        Document fragmentDoc = builder.parse(new ByteArrayInputStream(fragment.getBytes()));

        // step 3
        Node injectedNode = doc.adoptNode(fragmentDoc.getFirstChild());

        // step 4
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xPath.compile("//people/person[2]/name");
        System.out.println();
        Element nodeFound = (Element) expr.evaluate(doc, XPathConstants.NODE);

        // step 5
        Node parentNode = nodeFound.getParentNode();
        parentNode.removeChild(nodeFound);
        parentNode.appendChild(injectedNode);

        DOMSource domSource = new DOMSource(doc);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(domSource, result);
        System.out.println(result.getWriter().toString());
    }

}

除了刪除舊節點並添加新節點,您還可以使用: parentNode.replaceChild(injectedNode, nodeFound) 使用此功能,您可以使節點保持良好狀態

Node importedTemplateChildNode = targetDoc.importNode(templateChildNode, true);   
// Importing template node to the target document(this solves wrong_DOCUMENT_ERR:)

targetParentNode.replaceChild(importedTemplateChildNode, targetChildnode);       
// Replace target child node with the template node

Transformer tranFac =TransformerFactory.newInstance().newTransformer();
tranFac.transform(new DOMSource(targetDoc), new StreamResult(new FileWriter(targetXmlFile)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM