Java解析XML以获取Child Element值

时间:2015-12-09 04:41:34

标签: java xml parsing dom

我有一个包含以下XML代码的java字符串:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

解析此字符串以提取

值的最简单方法是什么
<?xml version="1.0" encoding="utf-8"?>
    <Chart>
        <request>
            <zip>12345</zip>
            <city>Miami</city>
        </request>
    </Chart>

2 个答案:

答案 0 :(得分:1)

您拥有XML,更好的是将其解析为XML,并将XPATH直接解析

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;


String xml="<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + 
        "    <Chart>\r\n" + 
        "        <request>\r\n" + 
        "            <zip>12345</zip>\r\n" + 
        "            <city>Miami</city>\r\n" + 
        "        </request>\r\n" + 
        "    </Chart>";

DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();

// PARSE XML
Document document = builder.parse(new InputSource(new  StringReader(xml)));

// XPATH
XPath xPath = XPathFactory.newInstance().newXPath();
// your path
String expression = "//Chart/request/zip";

NodeList nodes  = (NodeList)  xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

for(int i=0; i<nodes.getLength(); i++)
     {
      Node the_node = nodes.item(i);

     if(the_node instanceof Element)
          {
          Element the_element=(Element) the_node;
          System.out.println("element="+the_element.getTextContent());
          break; // STOP at the first
          }
      }

答案 1 :(得分:0)

如果不进入使用Java解析xml的深层世界,您可以使用正则表达式:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class FindZip {

  public static void main(String[] args) {
    Pattern pattern = 
    Pattern.compile("<zip>(\\d+)</zip>");
    String zip_code;

    Matcher matcher = pattern.matcher(
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<Chart>" +
        "    <request>" +
        "        <zip>12345</zip>" +
        "        <city>Miami</city>" +
        "    </request>" +
        "</Chart>"
      );

    boolean found = false;
    while (matcher.find()) {
      zip_code = matcher.group(1);
      System.out.printf(
          "I found the zip code \"%s\" starting at index %d and ending at index %d.%n",
          zip_code,
          matcher.start(1),
          matcher.end(1)
        );
      found = true;
    }
    if (!found) {
      System.out.println("No match found.");
    }
  }
}

这种方法有明显的缺点和局限,但至少你得到了你的邮政编码