使用Java和JAXP对XML文档进行访问


XML系列:使用Java和JAXP对XML文档进行访问和操作

一,Java访问XML文档
 导入java.xml.parsers包和org.w3c.dom包
 
 org.w3c.dom包包含了DOM解析器接口类型的定义。
 
 1,获取java.xml.parsers.DocumentBuilder类:为加载和分析XML文档提供接口,也就是XML分析程序接口。
  可以把JAXP配置成不同XML分析程序,java.xml.parsers.DocumentBuilderFactory用于获取一个分析程序的示例。
  使用DocumentBuilderFactory为当前的XML分析程序实例化一个DocumentBuilder对象。
   DocumentBuilderFactory factory =  DocumentBuilderFactory.newInsrance();
   DocumentBuilder builder = factory.newDocumentBuilder();
 2,加载和分析XML文档,如果加载成功则返回一个org.w3c.dom.Document对象,
   该对象是XML文档树形结构在内存中的表现。如果失败则抛出SAXException。
   Document对象由实现Node接口及其多个子接口的类的对象构成。
   
   File file = new File("type.xml");
   Document doc = builder.parse(file);
   
 3,Document对象的getDocumentElement方法获取根节点对象,getTagName方法返回节点的标签名
   
   Element root = doc.getDocumentElement();
   String rootName = doc.getTagName();

 
 4,Element对象的getChildNodes方法获取元素的子元素,返回结果为NodeList集合。
   getElementByTagName或getElementById,通过指定元素名或ID来获取该元素的子元素集合,返回结果为NodeList集合。
   NodeList children = root.getChildNodes();
   或
   NodeList children = root.getElementByTagName("type");
   使用item方法遍历集合,getLength提供集合元素的总数。
   
   
遍历NodeList集合:
    Element e = null;
    for(int i = 0; i < children.getLength(); i ++)
    {
     Node child = children.item(i);
     e = (Element) child;
     System.out.println(e.getTagName() + " : " + e.getFirstChild().getNodeValue());
    }
   
   遍历NodeList集合:只得到子元素,使用instanceof运算符进行类型检查。

    for(int i = 0; i < children.getLength(); i ++)
    {
     Node child = children.item(i);
     if (child instanceof Element)
     {
      Element e = (Element) child;
      System.out.println(e.getTagName() + " : " + e.getNodeValue());    
     }
    }  
   遍历NodeList集合:
    获取当前节点的第一个getFirstChild方法和下一个子节点getNextChild方法,没有节点的时候返回null。
     for (Node childNode = children.getFirstChild(); childNode != null;
        childeNode = childNode.getNextChild) {
      if(childNode instanceof Element){
       .....;
      }  
     }
 5,Element元素的getAttributes方法获取元素的的属性集合,返回结果为NamedNodeMap对象。
   可以像使用遍历NodeList集合一样遍历NamedNodeMap
   NamedNodeMap attributes = root.getAttributes();
   
   遍历NamedNodeMap集合:
   for (int i = 0; i < attributes.getLength(); i++)
   {
    Node attribute = attributes.item(i);
    String attributeName = attribute.getNodeName();
    String attributeValue = attribute.getNodeValue();
   }
   
例子: 
XML文档(type.xml):

 <?xml version="1.0" encoding="UTF-8"?>
<type xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="type1.xsd">
 <student state="true">
  <info>
   <name>张三</name>
   <sex>男</sex>
  </info>
  <grede>
   <chinese>1</chinese>
   <math>119</math>
  </grede>
 </student>
 <teacher state="true">
  <name>李四</name>
  <sex>女</sex>
  <subject>数学</subject>
 </teacher>
</type>    
java文件:

package com.qu.read;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.*;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class ReadXML {
 public ReadXML()
 { 
 }
 public Document readXMLFile(String fileName)
 {
  DocumentBuilderFactory factory = 
    DocumentBuilderFactory.newInstance();
  Document doc = null;
  try {
   DocumentBuilder builder = factory.newDocumentBuilder();
   File file = new File(fileName);
   doc = builder.parse(file);
  } catch (SAXException e) {
   
   e.printStackTrace();
  }catch (IOException e){
   e.printStackTrace();
  }catch (ParserConfigurationException e) {
   
   e.printStackTrace();
  }
  return doc;
   
 }
 
 public void readXMLElements(NodeList nodeList)
 {

  NamedNodeMap attributes =  null;
  
  for (int i = 0; i < nodeList.getLength(); i++)
  {
   Node childNode =  nodeList.item(i);
   String str = null;
   if (childNode instanceof Element){
    Element child =(Element) childNode;
    if( child.getChildNodes().getLength() > 1){
     
     str = "Element :" + child.getTagName() + ";";
     
    }else{
     str = "Element :" + child.getTagName();
     str += " : " + child.getFirstChild().getNodeValue() + "  ";
    }
    attributes = child.getAttributes();
    for (int j = 0; j < attributes.getLength(); j ++)
    {
     Node attr = attributes.item(j);
     if (attr instanceof Attr){
      String attrName = attr.getNodeName();
      String attrValue = attr.getNodeValue();
      str += "  Attribute " + attrName + " : " + attrValue + ";";
     }
     
    }
    System.out.println(str);
   }
   
  }
 }
 
 public static void main(String[] args) {
  ReadXML readXML = new ReadXML();
  Document doc = readXML.readXMLFile("E:/workspace/ReadXML/src/com/qu/xml/type.xml");
  NodeList nodeList = doc.getElementsByTagName("*");
  readXML.readXMLElements(nodeList);

 }
}

 

 

  
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 可以使用 Java API for XML Processing (JAXP) 中的 Validation API 对 XML 文件进行格式验证。具体实现步骤如下: 1. 创建一个 SAXParserFactory 实例,用于创建 SAXParser。 2. 设置 SAXParserFactory 的属性,使其支持 XML Schema 验证。 3. 创建一个 SAXParser 实例。 4. 实现一个 DefaultHandler,用于处理 SAX 事件。 5. 调用 SAXParser.parse() 方法,将 XML 文件解析为 SAX 事件流,并将 DefaultHandler 作为解析器的回调函数。 6. 如果 XML 文件格式不符合指定的 XML Schema,则会抛出 SAXException 异常。 下面是一个简单的示例代码,用于验证一个 XML 文件是否符合指定的 XML Schema: ```java import javax.xml.XMLConstants; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class XmlValidator extends DefaultHandler { private boolean isValid = true; public boolean validate(String xmlFilePath, String xsdFilePath) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File(xsdFilePath)); factory.setSchema(schema); SAXParser parser = factory.newSAXParser(); parser.parse(new File(xmlFilePath), this); } catch (Exception e) { isValid = false; } return isValid; } @Override public void error(SAXParseException e) throws SAXException { isValid = false; } @Override public void fatalError(SAXParseException e) throws SAXException { isValid = false; } } ``` 在上述代码中,validate() 方法接受两个参数,分别是要验证的 XML 文件路径和 XML Schema 文件路径。如果 XML 文件符合指定的 XML Schema,将返回 true,否则返回 false。如果 XML 文件格式不符合指定的 XML Schema,将抛出 SAXException 异常,isValid 属性将被设置为 false。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值