在Java中解析XML字符串可以使用多种方法,其中最常见的是使用Java内置的DOM、SAX和StAX API。
1.DOM解析器
DOM解析器将XML文档转换为树形结构,并允许您通过编程方式遍历和操作该树形结构。以下是一个简单的示例,演示如何使用DOM解析器解析XML字符串:
java复制代码
import l.parsers.DocumentBuilderFactory; | |
import l.parsers.DocumentBuilder; | |
import org.w3c.dom.Document; | |
import org.w3c.dom.Element; | |
import org.w3c.dom.NodeList; | |
public class DOMExample { | |
public static void main(String[] args) throws Exception { | |
String xmlString = "<root><element>text</element></root>"; | |
DocumentBuilderFactory factory = wInstance(); | |
DocumentBuilder builder = wDocumentBuilder(); | |
Document document = builder.parse(new InputSource(new StringReader(xmlString))); | |
DocumentElement().normalize(); | |
System.out.println("Root element: " + DocumentElement().getNodeName()); | |
NodeList nodeList = ElementsByTagName("element"); | |
for (int i = 0; i < Length(); i++) { | |
Element element = (Element) nodeList.item(i); | |
System.out.println("Element: " + TextContent()); | |
} | |
} | |
} | |
2.SAX解析器
SAX解析器是一种基于事件的解析器,它按顺序读取XML文档,并在读取每个元素时触发事件。以下是一个简单的示例,演示如何使用SAX解析器解析XML字符串:
java复制代码
import l.parsers.SAXParserFactory; | |
import l.parsers.SAXParser; | |
import l.sax.helpers.DefaultHandler; java xml是什么 | |
import l.sax.Attributes; | |
import l.sax.SAXException; | |
import l.sax.SAXParseException; | |
import java.io.StringReader; | |
public class SAXExample { | |
public static void main(String[] args) throws Exception { | |
String xmlString = "<root><element>text</element></root>"; | |
SAXParserFactory factory = wInstance(); | |
SAXParser saxParser = wSAXParser(); | |
DefaultHandler handler = new DefaultHandler() { | |
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { | |
System.out.println("Start element: " + qName); | |
} | |
public void endElement(String uri, String localName, String qName) throws SAXException { | |
System.out.println("End element: " + qName); | |
} | |
public void characters(char[] ch, int start, int length) throws SAXException { | |
System.out.println("Text: " + new String(ch, start, length)); | |
} | |
public void error(SAXParseException e) throws SAXException { | |
System.out.println("Error: " + e.getMessage()); | |
} | |
public void fatalError(SAXParseException e) throws SAXException { | |
System.out.println("Fatal error: " + e.getMessage()); | |
} | |
}; | |
saxParser.parse(new InputSource(new StringReader(xmlString)), handler); | |
} | |
} | |
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论