Simplest way to query XML in Java

后端 未结 9 488
南旧
南旧 2020-11-30 05:55

I have small Strings with XML, like:

String myxml = \"goodhi\";
<
相关标签:
9条回答
  • 2020-11-30 06:23

    You could try JXPath

    0 讨论(0)
  • 2020-11-30 06:26

    XPath using Java 1.5 and above, without external dependencies:

    String xml = "<resp><status>good</status><msg>hi</msg></resp>";
    
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    
    InputSource source = new InputSource(new StringReader(xml));
    String status = xpath.evaluate("/resp/status", source);
    
    System.out.println("satus=" + status);
    
    0 讨论(0)
  • 2020-11-30 06:28

    Using dom4j, similar to McDowell's solution:

    String myxml = "<resp><status>good</status><msg>hi</msg></resp>";
    
    Document document = new SAXReader().read(new StringReader(myxml));
    String status = document.valueOf("/resp/msg");
    
    System.out.println("status = " + status);
    

    XML handling is a bit simpler using dom4j. And several other comparable XML libraries exist. Alternatives to dom4j are discussed here.

    0 讨论(0)
  • 2020-11-30 06:29

    @The comments of this answer:

    You can create a method to make it look simpler

    String xml = "<resp><status>good</status><msg>hi</msg></resp>";
    
    System.out.printf("satus= %s\n", getValue("/resp/status", xml ) );
    

    The implementation:

    public String getValue( String path, String xml ) { 
        return XPathFactory
                   .newInstance()
                   .newXPath()
                   .evaluate( path , new InputSource(
                                     new StringReader(xml)));
    
    }
    
    0 讨论(0)
  • 2020-11-30 06:30

    After your done with simple ways to query XML in java. Look at XOM.

    0 讨论(0)
  • 2020-11-30 06:31

    Here is example of how to do that with XOM:

    String myxml = "<resp><status>good</status><msg>hi</msg></resp>";
    
    Document document = new Builder().build(myxml, "test.xml");
    Nodes nodes = document.query("/resp/status");
    
    System.out.println(nodes.get(0).getValue());
    

    I like XOM more than dom4j for its simplicity and correctness. XOM won't let you create invalid XML even if you want to ;-) (e.g. with illegal characters in character data)

    0 讨论(0)
提交回复
热议问题