xml java 解析_java解析XML

DOM解析XML

1 遍历xml文档节点树

student.xml

张三

18

100

lisi

20

100

遍历xml文档树:

packagedom.pasing;importjava.io.File;importjava.io.IOException;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;importorg.w3c.dom.Document;importorg.w3c.dom.NamedNodeMap;importorg.w3c.dom.Node;importorg.xml.sax.SAXException;public classDomPrinter {public static voidprintNodeInfo(String nodeType, Node node) {

System.out.println(nodeType+ "\t" + node.getNodeName() + ":" +node.getNodeValue());

}public static voidtraverseNode(Node node) {switch(node.getNodeType()) {caseNode.PROCESSING_INSTRUCTION_NODE:

printNodeInfo("处理指令", node);break;caseNode.ELEMENT_NODE:

printNodeInfo("元素", node);

NamedNodeMap attrs=node.getAttributes();for (int i=0; i

Node attr=attrs.item(i);

printNodeInfo("属性", attr);

}break;caseNode.TEXT_NODE:

printNodeInfo("文本", node);break;

}

Node child=node.getFirstChild();while (child != null) {

traverseNode(child);

child=child.getNextSibling();

}

}public static voidmain(String[] args) {

DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();try{

DocumentBuilder builder=builderFactory.newDocumentBuilder();

Document document= builder.parse(new File("src/students.xml"));

System.out.println("version=" + document.getXmlVersion() + " encoding=" +document.getXmlEncoding()+ " standalone=" +document.getXmlStandalone());

traverseNode(document);

}catch(ParserConfigurationException e) {

e.printStackTrace();

}catch(SAXException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}

}

2. 获取student.xml文档student元素下的指定name、age元素的值

DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();

DocumentBuilder builder=builderFactory.newDocumentBuilder();

Document document= builder.parse(new File("src/students.xml"));

NodeList nodeList= document.getElementsByTagName("student");for (int i=0; i

Element elementStu=(Element) nodeList.item(i);

Node elementName= elementStu.getElementsByTagName("name").item(0);

Node elementAge= elementStu.getElementsByTagName("age").item(0);

String name=elementName.getFirstChild().getNodeValue();

String age=elementAge.getFirstChild().getNodeValue();

System.out.println("-----------学生信息--------------");

System.out.println("姓名:" +name);

System.out.println("年龄:" +age);

}

3. 在DOM文档树上增删节点

DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();

DocumentBuilder builder=builderFactory.newDocumentBuilder();

Document document= builder.parse(new File("src/students.xml"));

Element studentElem= document.createElement("student");

Element nameElem= document.createElement("name");

Element ageElem= document.createElement("age");

Attr attr= document.createAttribute("sn");

attr.setValue("03");

Text txtName= document.createTextNode("王五");

Text txtAge= document.createTextNode("19");

studentElem.appendChild(txtName);

ageElem.appendChild(txtAge);

studentElem.setAttributeNode(attr);

studentElem.appendChild(nameElem);

studentElem.appendChild(ageElem);

document.getDocumentElement().appendChild(studentElem);//在文档根元素节点下,添加一个student元素节点

NodeList nodeList= document.getElementsByTagName("student");

Node nodeDel= nodeList.item(0);

nodeDel.getParentNode().removeChild(nodeDel);//移除第1个student元素节点

DOMSource source= newDOMSource(document);

StreamResult result= new StreamResult(new File("src/convert.xml"));

TransformerFactory transformerFactory=TransformerFactory.newInstance();

Transformer transformer=transformerFactory.newTransformer();

transformer.transform(source, result);//把DOM文档树保存到src/convert.xml文档中

dom4j解析XML

1. 生成XML文档

/*** 构造响应消息

*

*

* RDF-101

* RDF Validation Result

* sdfdsfsdfdsf

*

**/Document document=DocumentHelper.createDocument();

Element valrespEle= document.addElement("validateResponse");

valrespEle.addElement("id").setText("RDF-101");

valrespEle.addElement("desc").setText("RDF Validation Result");

valrespEle.addElement("content").setText("sjflafl速度就废了");

System.out.println(document.asXML());

2. 从格式化的XML字符串中取出指定元素的值

String xmlString =

""

+ "RDF-101"

+ "validate content"

+ "http://iec.ch/TC57/2005/CIM-schema-cim10#"

+ "gfasdgadgdfhfjghjghkjkfkdhsgdasgdsagfdgfsdgsfhfgd"

+ "";

Document document=DocumentHelper.parseText(xmlString);

Attribute typeAttr= (Attribute) document.selectSingleNode("/validate/@type");

Element idEle= (Element) document.selectSingleNode("/validate/id");

Element schemaEle= (Element) document.selectSingleNode("/validate/schema");

Element contentEle= (Element) document.selectSingleNode("/validate/content");

System.out.println(typeAttr.getText()+ "\n" + idEle.getText() + "\n" + schemaEle.getText() + "\n" + contentEle.getText());

SAX解析xml

1. 解析student.xml,解析器实现ContentHandler接口

packagesax.parsing;importjavax.xml.parsers.SAXParser;importjavax.xml.parsers.SAXParserFactory;import org.xml.sax.*;public classSAXDemo {public static void main(String[] args) throwsException {//sax的解析工厂

SAXParserFactory spf =SAXParserFactory.newInstance();//sax的解析器

SAXParser sparser =spf.newSAXParser();//获取阅读器

XMLReader xReader =sparser.getXMLReader();

xReader.setContentHandler(newMyContentHandler());//解析xml文档

xReader.parse("src//book.xml");

}

}class MyContentHandler implementsContentHandler {

@Overridepublic void startElement(String uri, String localName, String qName, Attributes atts) throwsSAXException {

System.out.println("");

}

@Overridepublic void endElement(String uri, String localName, String qName) throwsSAXException {

System.out.println("" + qName + ">");

}

@Overridepublic void characters(char[] ch, int start, int length) throwsSAXException {

System.out.println(newString(ch, start, length));

}

@Overridepublic void endDocument() throwsSAXException {//TODO Auto-generated method stub

}

@Overridepublic void endPrefixMapping(String prefix) throwsSAXException {//TODO Auto-generated method stub

}

@Overridepublic void ignorableWhitespace(char[] ch, int start, int length) throwsSAXException {//TODO Auto-generated method stub

}

@Overridepublic void processingInstruction(String target, String data) throwsSAXException {//TODO Auto-generated method stub

}

@Overridepublic voidsetDocumentLocator(Locator locator) {//TODO Auto-generated method stub

}

@Overridepublic void skippedEntity(String name) throwsSAXException {//TODO Auto-generated method stub

}

@Overridepublic void startDocument() throwsSAXException {//TODO Auto-generated method stub

}

@Overridepublic void startPrefixMapping(String prefix, String uri) throwsSAXException {//TODO Auto-generated method stub

}

}

输出结果:

张三

18

100

lisi

20

100

2. 解析器继承DefaultHandler类(默认解析类)

packagesax.parsing;importjava.io.File;importjava.io.IOException;importjavax.xml.parsers.ParserConfigurationException;importjavax.xml.parsers.SAXParser;importjavax.xml.parsers.SAXParserFactory;importorg.xml.sax.Attributes;importorg.xml.sax.SAXException;importorg.xml.sax.helpers.DefaultHandler;public class SaxPrinter extendsDefaultHandler {

@Overridepublic void startDocument() throwsSAXException {

System.out.println("<?xml version='1.0' encoding='gb2312' ?>");

}

@Overridepublic void processingInstruction(String target, String data) throwsSAXException {

System.out.println("" + target + " " + data + "?>");

}

@Overridepublic void startElement(String uri, String localName, String qname, Attributes attrs) throwsSAXException {

System.out.print("

System.out.print(" " + attrs.getQName(i) + "=\"" + attrs.getValue(i) + "\"");

}

System.out.print(">");

}

@Overridepublic void endElement(String uri, String localName, String qName) throwsSAXException {

System.out.print("" + qName + ">");

}

@Overridepublic void characters(char[] ch, int start, int length) throwsSAXException {

System.out.print(newString(ch, start, length));

}public static voidmain(String[] args) {

SAXParserFactory parserFactory=SAXParserFactory.newInstance();try{

SAXParser parser=parserFactory.newSAXParser();

parser.parse(new File("src/students.xml"), newSaxPrinter());

}catch(ParserConfigurationException e) {

e.printStackTrace();

}catch(SAXException e) {

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

输出结果:

张三

18

100

lisi

20

100

3. 依据XSD对XML进行校验

src/students.xsd

src/students.xml

张三

18

100

lisi

20

100

实现ErrorHandler接口,执行校验:

packagesax.parsing;importjava.io.File;importjava.io.IOException;importjavax.xml.XMLConstants;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;importjavax.xml.transform.stream.StreamSource;importjavax.xml.validation.Schema;importjavax.xml.validation.SchemaFactory;importjavax.xml.validation.Validator;importorg.testng.annotations.Test;importorg.xml.sax.ErrorHandler;importorg.xml.sax.SAXException;importorg.xml.sax.SAXParseException;public class SchemaValidator implementsErrorHandler {

@Overridepublic void warning(SAXParseException exception) throwsSAXException {

System.out.println("触发警告:");

System.err.println("warning: " + getLocationString(exception) + ": " +exception.getMessage());

}

@Overridepublic void error(SAXParseException exception) throwsSAXException {

System.out.println("触发错误:");

System.err.println("error: " + getLocationString(exception) + ": " +exception.getMessage());

}

@Overridepublic void fatalError(SAXParseException exception) throwsSAXException {

System.out.println("触发致命错误:");

System.err.println("fatal error: " + getLocationString(exception) + ": " +exception.getMessage());

}privateString getLocationString(SAXParseException ex) {

StringBuffer buffer= newStringBuffer();

String systemId=ex.getSystemId();if (systemId != null) {

buffer.append(systemId).append(" ");

}

buffer.append(ex.getLineNumber()).append(':').append(ex.getColumnNumber());returnbuffer.toString();

}/*** 从模式实例中获取校验器*/

//@Test

public voidvalidatorFromSchema() {//模式工厂

SchemaFactory schemaFactory =SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);try{//从工厂中实例化出一个模式对象

Schema schema = schemaFactory.newSchema(new File("src/students.xsd"));

Validator validator= schema.newValidator(); //实例化模式对应的校验器

validator.setErrorHandler(new SchemaValidator()); //设置校验的错误处理

validator.validate(new StreamSource(new File("src/students.xml")));

}catch(SAXException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}

}

输出结果:

触发错误:

error: file:/D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xml 4:41: cvc-complex-type.3.2.2: Attribute 'attr_test' is not allowed to appear in element 'student'.

触发错误:

error: file:/D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xml 10:40: cvc-complex-type.2.4.a: Invalid content was found starting with element 'elem_test1'. One of '{student}' is expected.

The Node interface is the primary datatype for the entire Document Object Model.

Node接口是DOM的主要数据类型,代表了文档树上的一个单个节点

It represents a single node in the document tree.

While all objects implementing the Node interface expose methods for dealing with children, not all objects implementing the Node interface may have children.

尽管实现Node接口的所有对象都暴露了处理子节点的方法,但并不是实现Node的所有对象都会有子节点。例如Text文本节点就没有子节点

For example, Text nodes may not have children, and adding children to such nodes results in a DOMException being raised.

The attributes nodeName, nodeValue and attributes are included as a mechanism to get at node information without casting down to the specific derived interface.

In cases where there is no obvious mapping of these attributes for a specific nodeType (e.g., nodeValue for an Element or attributes for a Comment ), this returns null.

Note that the specialized interfaces may contain additional and more convenient mechanisms to get and set the relevant information.

The values of nodeName, nodeValue, and attributes vary according to the node type as follows:

根据nodeType的类型,nodeName, nodeValue, attributes取值相应变化:

Interface

nodeName

nodeValue

attributes

Attr

same as Attr.name

same as Attr.value

null

CDATASection

"#cdata-section"

same as CharacterData.data, the content of the CDATA Section

null

Comment

"#comment"

same as CharacterData.data, the content of the comment

null

Document

"#document"

null

null

DocumentFragment

"#document-fragment"

null

null

DocumentType

same as DocumentType.name

null

null

Element

same as Element.tagName

null

NamedNodeMap

Entity

entity name

null

null

EntityReference

name of entity referenced

null

null

Notation

notation name

null

null

ProcessingInstruction

same as ProcessingInstruction.target

same as ProcessingInstruction.data

null

Text

"#text"

same as CharacterData.data, the content of the text node

null

xml文档树(DOM树上的每个节点都是Node接口的实例)

文档根节点 Document document = builder.parse(new InputSource(new FileInputStream("src/students.xml")));

文档根元素节点 Element root = document.getDocumentElement();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值