Retrieve element with Jdom / XPath and "












2















I'm working on an application that has these kinds of xml file (document.xml):



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


I need to retrieve Element's using XPath expressions. I'm not able to retrieve the second element, which I need to select using the value of myAttribute. This is due to the &quot; character ...



Here is a test class. The second assertion is throwing an AssertionError because the object is null.



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);
}
}


The application is using Jdom 1.1.3



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


How can I change my xpath expression so that the second element is returned ? Is this possible with this version of Jdom ?



Thank you for your help !










share|improve this question























  • Try workaround /root/subRoot[starts-with(@myAttribute, "CN=") and contains(@myAttribute, "Problem")]

    – Andersson
    Nov 20 '18 at 9:28













  • Thank you @Andersson. I like the idea, and it will probably work with my example. But I think I have simplified it too much. I might end up with selecting another element that the one required. I really need to select something like "CN=Problem", and not "CN=Something, ... Problem".

    – Nis
    Nov 20 '18 at 10:20











  • OK. Another workaround is /root/subRoot[contains(substring-after(@myAttribute, "CN="), "Problem") and string-length(@myAttribute)=12]. This should match required node. Exception cases are CN= Problem ", CN=&Problem&", CN= Problems", etc...so only if two characters differs

    – Andersson
    Nov 20 '18 at 10:24













  • Since attribute values are more complicated in real life scenario, I think the answer from @forty-two is simpler. Thank you for your help.

    – Nis
    Nov 27 '18 at 11:37


















2















I'm working on an application that has these kinds of xml file (document.xml):



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


I need to retrieve Element's using XPath expressions. I'm not able to retrieve the second element, which I need to select using the value of myAttribute. This is due to the &quot; character ...



Here is a test class. The second assertion is throwing an AssertionError because the object is null.



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);
}
}


The application is using Jdom 1.1.3



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


How can I change my xpath expression so that the second element is returned ? Is this possible with this version of Jdom ?



Thank you for your help !










share|improve this question























  • Try workaround /root/subRoot[starts-with(@myAttribute, "CN=") and contains(@myAttribute, "Problem")]

    – Andersson
    Nov 20 '18 at 9:28













  • Thank you @Andersson. I like the idea, and it will probably work with my example. But I think I have simplified it too much. I might end up with selecting another element that the one required. I really need to select something like "CN=Problem", and not "CN=Something, ... Problem".

    – Nis
    Nov 20 '18 at 10:20











  • OK. Another workaround is /root/subRoot[contains(substring-after(@myAttribute, "CN="), "Problem") and string-length(@myAttribute)=12]. This should match required node. Exception cases are CN= Problem ", CN=&Problem&", CN= Problems", etc...so only if two characters differs

    – Andersson
    Nov 20 '18 at 10:24













  • Since attribute values are more complicated in real life scenario, I think the answer from @forty-two is simpler. Thank you for your help.

    – Nis
    Nov 27 '18 at 11:37
















2












2








2








I'm working on an application that has these kinds of xml file (document.xml):



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


I need to retrieve Element's using XPath expressions. I'm not able to retrieve the second element, which I need to select using the value of myAttribute. This is due to the &quot; character ...



Here is a test class. The second assertion is throwing an AssertionError because the object is null.



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);
}
}


The application is using Jdom 1.1.3



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


How can I change my xpath expression so that the second element is returned ? Is this possible with this version of Jdom ?



Thank you for your help !










share|improve this question














I'm working on an application that has these kinds of xml file (document.xml):



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


I need to retrieve Element's using XPath expressions. I'm not able to retrieve the second element, which I need to select using the value of myAttribute. This is due to the &quot; character ...



Here is a test class. The second assertion is throwing an AssertionError because the object is null.



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);
}
}


The application is using Jdom 1.1.3



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


How can I change my xpath expression so that the second element is returned ? Is this possible with this version of Jdom ?



Thank you for your help !







java xpath jdom






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 9:20









NisNis

899




899













  • Try workaround /root/subRoot[starts-with(@myAttribute, "CN=") and contains(@myAttribute, "Problem")]

    – Andersson
    Nov 20 '18 at 9:28













  • Thank you @Andersson. I like the idea, and it will probably work with my example. But I think I have simplified it too much. I might end up with selecting another element that the one required. I really need to select something like "CN=Problem", and not "CN=Something, ... Problem".

    – Nis
    Nov 20 '18 at 10:20











  • OK. Another workaround is /root/subRoot[contains(substring-after(@myAttribute, "CN="), "Problem") and string-length(@myAttribute)=12]. This should match required node. Exception cases are CN= Problem ", CN=&Problem&", CN= Problems", etc...so only if two characters differs

    – Andersson
    Nov 20 '18 at 10:24













  • Since attribute values are more complicated in real life scenario, I think the answer from @forty-two is simpler. Thank you for your help.

    – Nis
    Nov 27 '18 at 11:37





















  • Try workaround /root/subRoot[starts-with(@myAttribute, "CN=") and contains(@myAttribute, "Problem")]

    – Andersson
    Nov 20 '18 at 9:28













  • Thank you @Andersson. I like the idea, and it will probably work with my example. But I think I have simplified it too much. I might end up with selecting another element that the one required. I really need to select something like "CN=Problem", and not "CN=Something, ... Problem".

    – Nis
    Nov 20 '18 at 10:20











  • OK. Another workaround is /root/subRoot[contains(substring-after(@myAttribute, "CN="), "Problem") and string-length(@myAttribute)=12]. This should match required node. Exception cases are CN= Problem ", CN=&Problem&", CN= Problems", etc...so only if two characters differs

    – Andersson
    Nov 20 '18 at 10:24













  • Since attribute values are more complicated in real life scenario, I think the answer from @forty-two is simpler. Thank you for your help.

    – Nis
    Nov 27 '18 at 11:37



















Try workaround /root/subRoot[starts-with(@myAttribute, "CN=") and contains(@myAttribute, "Problem")]

– Andersson
Nov 20 '18 at 9:28







Try workaround /root/subRoot[starts-with(@myAttribute, "CN=") and contains(@myAttribute, "Problem")]

– Andersson
Nov 20 '18 at 9:28















Thank you @Andersson. I like the idea, and it will probably work with my example. But I think I have simplified it too much. I might end up with selecting another element that the one required. I really need to select something like "CN=Problem", and not "CN=Something, ... Problem".

– Nis
Nov 20 '18 at 10:20





Thank you @Andersson. I like the idea, and it will probably work with my example. But I think I have simplified it too much. I might end up with selecting another element that the one required. I really need to select something like "CN=Problem", and not "CN=Something, ... Problem".

– Nis
Nov 20 '18 at 10:20













OK. Another workaround is /root/subRoot[contains(substring-after(@myAttribute, "CN="), "Problem") and string-length(@myAttribute)=12]. This should match required node. Exception cases are CN= Problem ", CN=&Problem&", CN= Problems", etc...so only if two characters differs

– Andersson
Nov 20 '18 at 10:24







OK. Another workaround is /root/subRoot[contains(substring-after(@myAttribute, "CN="), "Problem") and string-length(@myAttribute)=12]. This should match required node. Exception cases are CN= Problem ", CN=&Problem&", CN= Problems", etc...so only if two characters differs

– Andersson
Nov 20 '18 at 10:24















Since attribute values are more complicated in real life scenario, I think the answer from @forty-two is simpler. Thank you for your help.

– Nis
Nov 27 '18 at 11:37







Since attribute values are more complicated in real life scenario, I think the answer from @forty-two is simpler. Thank you for your help.

– Nis
Nov 27 '18 at 11:37














1 Answer
1






active

oldest

votes


















1














Try this expression:



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


Firstly, when the document is parsed, the entity &quot; is replaced with the " character, so that should be used directly in the XPath expression.



Secondly, in XPath you can use either single or double quotes for string constants, which is convenient if you have strings that contain quotes.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389777%2fretrieve-element-with-jdom-xpath-and-quot%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Try this expression:



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


    Firstly, when the document is parsed, the entity &quot; is replaced with the " character, so that should be used directly in the XPath expression.



    Secondly, in XPath you can use either single or double quotes for string constants, which is convenient if you have strings that contain quotes.






    share|improve this answer




























      1














      Try this expression:



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


      Firstly, when the document is parsed, the entity &quot; is replaced with the " character, so that should be used directly in the XPath expression.



      Secondly, in XPath you can use either single or double quotes for string constants, which is convenient if you have strings that contain quotes.






      share|improve this answer


























        1












        1








        1







        Try this expression:



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


        Firstly, when the document is parsed, the entity &quot; is replaced with the " character, so that should be used directly in the XPath expression.



        Secondly, in XPath you can use either single or double quotes for string constants, which is convenient if you have strings that contain quotes.






        share|improve this answer













        Try this expression:



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


        Firstly, when the document is parsed, the entity &quot; is replaced with the " character, so that should be used directly in the XPath expression.



        Secondly, in XPath you can use either single or double quotes for string constants, which is convenient if you have strings that contain quotes.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 10:23









        forty-twoforty-two

        10.7k21727




        10.7k21727
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389777%2fretrieve-element-with-jdom-xpath-and-quot%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to send String Array data to Server using php in android

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Is anime1.com a legal site for watching anime?