dom4j解析xml

maven

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.6</version>
</dependency>

demo

/**
 * xml解析pdm文件
 * 1. 填充中文表名
 * 2. 将字段comment设置到name,并设置comment为空
 *
 * @author Kang.Y
 * @Date 9:45 2018/12/24
 * @since 1.8
 */
public static void main(String[] args) throws Exception {
    // 创建SAXReader的对象reader
    SAXReader reader = new SAXReader();
    // 通过reader对象的read方法加载文件,获取docuemnt对象。
    Document document = reader.read(new File("C:\\Users\\Kang.Y\\Desktop\\PhysicalDataModel_1.pdm"));
    //        // 循环遍历方式
    //        Iterator iterator = document.nodeIterator();
    //        while (iterator.hasNext()) {
    //            Element next = (Element) iterator.next();
    //            // do something
    //        }

    // xpath搜索方式
    String xpath = "/Model/o:RootObject/c:Children/o:Model/c:Tables/o:Table";
    List<Element> tables = document.selectNodes(xpath);
    Element tableName = null;
    Element tablePhysicalOptions = null;
    Element columnName = null;
    Element columnComment = null;
    for (Element table : tables) {
        tableName = (Element) table.selectSingleNode("a:Name");
        tablePhysicalOptions = (Element) table.selectSingleNode("a:PhysicalOptions");
        String comment = tablePhysicalOptions.getText();
        String[] split = comment.split(" COMMENT=");
        if (split.length > 1) {
            tableName.setText(split[1].replaceAll("'", ""));
        }
        tablePhysicalOptions.setText(split[0]);
        List<Element> columns = table.selectNodes("c:Columns/o:Column");
        for (Element column : columns) {
            columnName = (Element) column.selectSingleNode("a:Name");
            columnComment = (Element) column.selectSingleNode("a:Comment");
            if(columnComment != null){
                columnName.setText(columnComment.getText());
                columnComment.setText("");
            }
        }
    }
    //用于格式化xml内容和设置头部标签
    OutputFormat format = OutputFormat.createPrettyPrint();
    //设置xml文档的编码为utf-8
    format.setEncoding("utf-8");
    Writer out = new FileWriter("E://new.pdm");
    XMLWriter writer = new XMLWriter(out, format);
    writer.write(document);
    writer.close();
}



/**
 * xpath解析示例
 *
 * @param args
 */
public static void main(String[] args) {
    String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            "" +
            "<urls>" +
            "  <url>" +
            "    <url_short>http://t.cn/EJSq234</url_short>" +
            "    <url_long>https://itpub.buyforyou.cn/redmine/my/page</url_long>" +
            "    <type>0</type>" +
            "  </url>" +
            "</urls>";
    // 创建SAXReader的对象reader
    SAXReader reader = new SAXReader();
    Map<String, String> returnMap = new HashMap<>();
    try {
        // 通过reader对象的read方法获取docuemnt对象。
        Document document = reader.read(new ByteArrayInputStream(xml.getBytes()));
        Node node = document.selectSingleNode("/urls/url/url_short");
        System.out.println(node.getStringValue());
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

xpath语法

基本语法

表达式描述
nodename选取此节点的所有子节点
/从根节点选取
//从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
.选取当前节点
选取当前节点的父节点
@选取属性

实例

路径表达式结果
bookstore选取 bookstore 元素的所有子节点
/bookstore选取根元素 bookstore
注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径!
bookstore/book选取所有属于 bookstore 的子元素的 book 元素。
//book选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book选择所有属于 bookstore 元素的后代的 book 元素,而不管它们位于 bookstore
//@lang选取所有名为 lang 的属性。

谓语(Predicates)

路径表达式结果
/bookstore/book[1]选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()]选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1]选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()❤️]选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang]选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang=‘eng’]选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00]选取所有 bookstore 元素的 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title选取所有 bookstore 元素中的 book 元素的 title 元素,且其中的 price 元素的值须大于 35.00。

选取未知节点

XPath 通配符可用来选取未知的 XML 元素。

通配符描述
*匹配任何元素节点
@*匹配任何属性节点
node()匹配任何类型的节点

实例

路径表达式结果
/bookstore/*选取 bookstore 元素的所有子节点
//*选取文档中的所有元素
//title[@*]选取所有带有属性的 title 元素。

若干路径

路径表达式结果
//book/title | //book/price选取所有 book 元素的 title 和 price 元素。
//title | //price选取所有文档中的 title 和 price 元素。
/bookstore/book/title | //price选取所有属于 bookstore 元素的 book 元素的 title 元素,以及文档中所有的 price 元素。

XPath 轴

轴可定义某个相对于当前节点的节点集。

轴名称结果
ancestor选取当前节点的所有先辈(父、祖父等)
ancestor-or-self选取当前节点的所有先辈(父、祖父等)以及当前节点本身
attribute选取当前节点的所有属性
child选取当前节点的所有子元素。
descendant选取当前节点的所有后代元素(子、孙等)。
descendant-or-self选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
following选取文档中当前节点的结束标签之后的所有节点。
namespace选取当前节点的所有命名空间节点
parent选取当前节点的父节点。
preceding选取文档中当前节点的开始标签之前的所有节点。
preceding-sibling选取当前节点之前的所有同级节点。
self选取当前节点。

位置路径表达式

  • 位置路径可以是绝对的,也可以是相对的。
  • 绝对路径起始于正斜杠( / ),而相对路径不会这样。在两种情况中,位置路径均包括一个或多个步,每个步均被斜杠分割:
    • 绝对位置路径:/step/step/…
    • 相对位置路径:step/step/…
  • 每个步均根据当前节点集之中的节点来进行计算。
  • 步(step)包括:
    • 轴(axis):定义所选节点与当前节点之间的树关系
    • 节点测试(node-test):识别某个轴内部的节点
    • 零个或者更多谓语(predicate):更深入地提炼所选的节点集
  • 步的语法:
    • 轴名称::节点测试[谓语]

实例

例子结果
child::book选取所有属于当前节点的子元素的 book 节点
attribute::lang选取当前节点的 lang 属性
child:?选取当前节点的所有子元素
attribute:?选取当前节点的所有属性
child::text()选取当前节点的所有文本子节点
child::node()选取当前节点的所有子节点
descendant::book选取当前节点的所有 book 后代
ancestor::book选择当前节点的所有 book 先辈
ancestor-or-self::book选取当前节点的所有book先辈以及当前节点(假如此节点是book节点的话)
child:?/child::price选取当前节点的所有 price 孙。

XPath 运算符

下面列出了可用在 XPath 表达式中的运算符:

运算符描述实例返回值
计算两个节点集//book//cd
+加法6 + 410
-减法6 - 42
*乘法6 * 424
div除法8 div 42
=等于price=9.80如果 price 是 9.80,则返回 true。
如果 price 是 9.90,则返回 fasle。
!=不等于price!=9.80如果 price 是 9.90,则返回 true。
如果 price 是 9.80,则返回 fasle。
<小于price<9.80如果 price 是 9.00,则返回 true。
如果 price 是 9.90,则返回 fasle。
<=小于或等于price<=9.80如果 price 是 9.00,则返回 true。
如果 price 是 9.90,则返回 fasle。
>大于price>9.80如果 price 是 9.90,则返回 true。
如果 price 是 9.80,则返回 fasle。
>=大于或等于price>=9.80如果 price 是 9.90,则返回 true。
如果 price 是 9.70,则返回 fasle。
orprice=9.80 or price=9.70如果 price 是 9.80,则返回 true。
如果 price 是 9.50,则返回 fasle。
andprice>9.00 and price<9.90如果 price 是 9.80,则返回 true。
如果 price 是 8.50,则返回 fasle。
mod计算除法的余数5 mod 21
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值