java 处理 xml

java 处理 xml 代码记录一下:

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
     <Employee ID="1">
          <Firstname>Dean</Firstname >
          <Lastname>Winchester</Lastname>
          <Age>30</Age>
          <Salary>2500</Salary>
     </Employee>
     <Employee ID="2">
          <Firstname>Sam</Firstname>
          <Lastname>Davis</Lastname>
          <src-pw>
            <id>testsrc</id>
          </src-pw>
          <snk-pw>
            <id>testsnk</id>
          </snk-pw>
          <Age>22</Age>
          <Salary>1500</Salary>
     </Employee>
     <Employee ID="3">
          <Firstname>Jake</Firstname>
          <Lastname>Peralta</Lastname>
          <Age>24</Age>
          <Salary>2000</Salary>
     </Employee>
     <Employee ID="4">
          <Firstname>Amy</Firstname>
          <Lastname>Griffin</Lastname>
          <Age>25</Age>
          <Salary>2250</Salary>
     </Employee>
</Employees>

解析代码

package com.wangs0622.document;

import java.io.File;
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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

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

public class DocumentParser {
    private Document document;

    public DocumentParser(File file) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(file);
    }

    public String getDocString() {
        return convertXmlDomToString(document);
    }

    public void handleDocument() throws XPathExpressionException {
        NodeList nodeList = getNodeList("//Employee[@ID=2]", document);
        Node employeesNode = getNodeList("//Employees", document).item(0);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            Node cloneNode = node.cloneNode(true);
            NodeList srcPwNodeList = getNodeList("src-pw", node);
            if (srcPwNodeList.getLength() > 0) {
                node.removeChild(srcPwNodeList.item(0));
            }

            NodeList snkPwNodeList = getNodeList("snk-pw", cloneNode);
            if (snkPwNodeList.getLength() > 0) {
                cloneNode.removeChild(snkPwNodeList.item(0));
            }
            employeesNode.appendChild(cloneNode);
        }
        System.out.println(getNodeList("//Employee", document).getLength());
    }

    public NodeList getNodeList(String xpathStr, Node rootNode) throws XPathExpressionException {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xpath.compile(xpathStr).evaluate(rootNode, XPathConstants.NODESET);
        return nodeList;
    }

    public String convertXmlDomToString(Document xmlDocument) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
          transformer = tf.newTransformer();
        
          // Uncomment if you do not require XML declaration
          // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        
          //A character stream that collects its output in a string buffer,
          //which can then be used to construct a string.
          StringWriter writer = new StringWriter();
        
          //transform document to string
          transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
        
          return writer.getBuffer().toString();
        } catch (TransformerException e) {
          e.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
        return null;
    }
}

测试代码

package com.wangs0622.document;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.junit.Test;
import org.xml.sax.SAXException;

public class DocumentParserTest {
    @Test
    public void parseXmlTest() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        File file = new File("D:\\wsProgram\\learnjava\\learnjava\\src\\test\\java\\com\\wangs0622\\document\\testInput.xml");
        DocumentParser parser = new DocumentParser(file);
        System.out.println(parser.getDocString());
        parser.handleDocument();
        System.out.println("-----------------");
        System.out.println(parser.getDocString());
    }
}

输出结果

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Employees>
     <Employee ID="1">
          <Firstname>Dean</Firstname>
          <Lastname>Winchester</Lastname>
          <Age>30</Age>
          <Salary>2500</Salary>
     </Employee>
     <Employee ID="2">
          <Firstname>Sam</Firstname>
          <Lastname>Davis</Lastname>
          <src-pw>
            <id>testsrc</id>
          </src-pw>
          <snk-pw>
            <id>testsnk</id>
          </snk-pw>
          <Age>22</Age>
          <Salary>1500</Salary>
     </Employee>
     <Employee ID="3">
          <Firstname>Jake</Firstname>
          <Lastname>Peralta</Lastname>
          <Age>24</Age>
          <Salary>2000</Salary>
     </Employee>
     <Employee ID="4">
          <Firstname>Amy</Firstname>
          <Lastname>Griffin</Lastname>
          <Age>25</Age>
          <Salary>2250</Salary>
     </Employee>
</Employees>
5
-----------------
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Employees>
     <Employee ID="1">
          <Firstname>Dean</Firstname>
          <Lastname>Winchester</Lastname>
          <Age>30</Age>

          <Firstname>Sam</Firstname>
          <Lastname>Davis</Lastname>
          
          <snk-pw>
            <id>testsnk</id>
          </snk-pw>
          <Age>22</Age>
          <Salary>1500</Salary>
     </Employee>
     <Employee ID="3">
          <Firstname>Jake</Firstname>
          <Lastname>Peralta</Lastname>
          <Age>24</Age>
          <Salary>2000</Salary>
     </Employee>
     <Employee ID="4">
          <Firstname>Amy</Firstname>
          <Lastname>Griffin</Lastname>
          <Age>25</Age>
          <Salary>2250</Salary>
     </Employee>
<Employee ID="2">
          <Firstname>Sam</Firstname>
          <Lastname>Davis</Lastname>
          <src-pw>
            <id>testsrc</id>
          </src-pw>
          
          <Age>22</Age>
          <Salary>1500</Salary>
     </Employee></Employees>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值