java - 使用 Jdom/XPath 和 "检索元素

标签 java xpath jdom

我正在开发一个包含这些类型的 xml 文件 (document.xml) 的应用程序:

<root>
    <subRoot myAttribute="CN=Ok">
        Ok
    </subRoot>
    <subRoot myAttribute="CN=&quot;Problem&quot;">
        Problem
    </subRoot>    
</root>

我需要使用 XPath 表达式检索 Element。我无法检索第二个元素,我需要使用 myAttribute 的值来选择它。这是由于 " 字符 ...

这是一个测试类。第二个断言抛出 AssertionError,因为对象为空。

import static org.junit.Assert.assertNotNull;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.junit.Test;

public class XPathTest {

    @Test
    public void quotesXpath() throws JDOMException, IOException {
        Document document = getDocumentFromContent(getClasspathResource("document.xml"));

        String okXPath = "/root/subRoot[@myAttribute=\"CN=Ok\"]";
        assertNotNull(getElement(document, okXPath)); // Ok ...

        String problemXPath = "/root/subRoot[@myAttribute=\"CN=&quot;Problem&quot;\"]";
        assertNotNull(getElement(document, problemXPath)); // Why null ?
    }

    public String getClasspathResource(String filePath) throws IOException {
        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath)) {
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        }
    }

    public static Document getDocumentFromContent(String content) throws IOException, JDOMException {
        try (InputStream is = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) {
            SAXBuilder builder = new SAXBuilder();
            return builder.build(is);
        }
    }

    public Element getElement(Document document, String xpathExpression) throws JDOMException {
        XPath xpath = XPath.newInstance(xpathExpression);
        return (Element) xpath.selectSingleNode(document);
    }
}

应用程序正在使用 Jdom 1.1.3

<dependency>
   <groupId>org.jdom</groupId>
   <artifactId>jdom</artifactId>
   <version>1.1.3</version>
</dependency>

如何更改我的 xpath 表达式以便返回第二个元素?这个版本的 Jdom 可以吗?

感谢您的帮助!

最佳答案

试试这个表达式:

    String problemXPath = "/root/subRoot[@myAttribute='CN=\"Problem\"']";

首先,在解析文档时,实体 " 被替换为 " 字符,因此应该直接在 XPath 表达式中使用。

其次,在 XPath 中,您可以对字符串常量使用单引号或双引号,如果您的字符串包含引号,这将很方便。

关于java - 使用 Jdom/XPath 和 "检索元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53389777/

相关文章:

java - 我如何在 java swing 中创建选项卡

java - 如何从字符串创建元素

java - 为什么它总是返回原始值?

java - 如何从 dockerized spring boot 连接 dockerized couchbase 服务器

java - 使用 Marklogic 的 Java 搜索 API 与 XQuery/XSLT API 进行文档 XPath 搜索

python - 用于从 python 中的 selenium webelement 捕获悬停 css 属性的 xpath

java - 从 jdom 中的文档读取文本时出错?

java - JDOM 到对象列表

java - 将文件大小格式化为 MB、GB 等

php - XPath 在匹配占位符的属性节点时失败