首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Jdom / XPath和“;

使用Jdom / XPath和“;
EN

Stack Overflow用户
提问于 2018-11-20 09:20:56
回答 1查看 839关注 0票数 2

我正在开发一个具有这类xml文件(document.xml)的应用程序:

代码语言:javascript
复制
<root>
    <subRoot myAttribute="CN=Ok">
        Ok
    </subRoot>
    <subRoot myAttribute="CN=&quot;Problem&quot;">
        Problem
    </subRoot>    
</root>

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

这是一堂考试课。第二个断言是抛出一个AssertionError,因为该对象为null。

代码语言:javascript
复制
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

代码语言:javascript
复制
<dependency>
   <groupId>org.jdom</groupId>
   <artifactId>jdom</artifactId>
   <version>1.1.3</version>
</dependency>

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

谢谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-23 10:23:33

试试这个表达式:

代码语言:javascript
复制
    String problemXPath = "/root/subRoot[@myAttribute='CN=\"Problem\"']";

首先,在解析文档时,将实体&quot;替换为"字符,以便直接在XPath表达式中使用。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53389777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档