Skip to content

Java dom4j 解析XML

发布时间:

  • dom4j解析XML 自己整理,经过测试无bug
js
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.List;

public class testXml {
    //XML文件代码
    static String XML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<Person>\n" +
            "    <XingMing>王东</XingMing >\n" +
            "    <XingBie>男</XingBie>\n" +
            "    <JiaTingChengYuan>\n" +
            "        <Item>\n" +
            "            <ChengWei>儿子</ChengWei>\n" +
            "            <ChuShengRiQi>199001</ChuShengRiQi>\n" +
            "        </Item>\n" +
            "        <Item>\n" +
            "            <ChengWei>女儿</ChengWei>\n" +
            "            <ChuShengRiQi>199403</ChuShengRiQi>\n" +
            "        </Item>\n" +
            "    </JiaTingChengYuan>\n" +
            "</Person>";
    //解析
    public static void undo() {
        try {
            Document doc = DocumentHelper.parseText(XML);
            Element root = doc.getRootElement();
            String XingMing = root.element("XingMing").getTextTrim();
            String XingBie = root.element("XingBie").getTextTrim();
            System.out.println("XingMing" + XingMing);
            System.out.println("XingBie" + XingBie);

            Element jiaTingChengYuan = root.element("JiaTingChengYuan");
            String xmlStr = jiaTingChengYuan.asXML();
            //生成字符串
            System.out.println("xmlStr" + xmlStr);
            List<Element> items = jiaTingChengYuan.elements();
            for (Element item : items) {
                String ChengWei = item.element("ChengWei").getTextTrim();
                String ChuShengRiQi = item.element("ChuShengRiQi").getTextTrim();
                System.out.println("ChengWei" + ChengWei);
                System.out.println("ChuShengRiQi" + ChuShengRiQi);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}