java解析xml字符串
时间: 2023-08-05 16:39:08 浏览: 142
你可以使用Java内置的DOM或者SAX解析器来解析XML字符串。
使用DOM解析器:
```java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
String xmlString = "your xml string";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(xmlString)));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("your tag name");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String value = eElement.getElementsByTagName("your sub tag name").item(0).getTextContent();
}
}
```
使用SAX解析器:
```java
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
String xmlString = "your xml string";
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bTag = false;
boolean bSubTag = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("your tag name")) {
bTag = true;
} else if (qName.equalsIgnoreCase("your sub tag name")) {
bSubTag = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
if (qName.equalsIgnoreCase("your tag name")) {
bTag = false;
} else if (qName.equalsIgnoreCase("your sub tag name")) {
bSubTag = false;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bSubTag) {
String value = new String(ch, start, length);
}
}
};
saxParser.parse(new InputSource(new StringReader(xmlString)), handler);
```
阅读全文