How to read an XML file with Java?

后端 未结 9 2167
执念已碎
执念已碎 2020-12-03 12:15

I don\'t need to read complex XML files. I just want to read the following configuration file with a simplest XML reader


    loc         


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 12:45

    If you just need a simple solution that's included with the Java SDK (since 5.0), check out the XPath package. I'm sure others perform better, but this was all I needed. Here's an example:

    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpressionException;
    import javax.xml.xpath.XPathFactory;
    import org.xml.sax.InputSource;
    
    ...
    
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        InputSource inputSource = new InputSource("strings.xml");
    
        // result will equal "Save My Changes" (see XML below)
        String result = xpath.evaluate("//string", inputSource);
    }
    catch(XPathExpressionException e) {
        // do something
    }
    

    strings.xml

    
    
        Save My Changes
    
    

提交回复
热议问题