XML解析之xsi:nil="true"

本文介绍XML中xsi:nil属性的作用及如何使用Xerces和XPath获取元素的xsi:nil值。通过示例展示了当xsi:nil设置为true时,元素内容为空的情形。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XML解析之xsi:nil="true"


                                                                                                                                           ——amachaoiv 2008-01-31     首先,我们来看看一个应用 xsi:nil="true"的例子。

    在下面的XML中<street xsi:nil="true"/> 表示在获取"street"元素的内容时, 在xsi:nil属性的控制下,其返回值应该为null。这跟一般的XML读取不一样,我们需要考虑其 属性 对元素内容的影响。
<?xml version="1.0"?>
<purchaseOrders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation
="F:/test/XML/XSD/primer.xsd">
  
<!-- 1st -->
  
<purchaseOrder id="1" orderDate="2004-06-28">
    
<shipTo country="US">
      
<name>Alice Smith</name>
      
<street xsi:nil="true"/>
      
<city>Cambridge</city>
      
<state>MA</state>
      
<zip>12345</zip>
    
</shipTo>
    
<billTo country="US">
      
<name>Robert Smith</name>
      
<street>8 Oak Avenue</street>
      
<city>Cambridge</city>
      
<state>MA</state>
      
<zip>12345</zip>
    
</billTo>
    
<items/>
  
</purchaseOrder>
</purchaseOrders>

    如何获取系统地获取
xsi:nil的值非常重要。(xsi这个命名空间中还有其他的属性, 如:xsi:type等)
    由于现在对xsd坐检查的API比较多,但能直接获取xsi:nil比较少,下面给大家展现一下应用Xerces进行读取的例子。
    应该到 org.apache.xerces.parsers.DOMParser 类作为xml的分析类,com.sun.org.apache.xpath.internal.XPathAPI用来进行Xpath的读取。
org.apache.xerces.xs.ElementPSVI就是包含有xsi:nil信息的类。

import java.io.IOException;
import javax.xml.transform.TransformerException;
import org.apache.xerces.xs.ElementPSVI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import com.sun.org.apache.xpath.internal.objects.XObject;

public class DomTest {
    
public static void main(String[] args) {
        
try {
            org.apache.xerces.parsers.DOMParser parser 
= new org.apache.xerces.parsers.DOMParser();
            parser.setProperty(
"http://apache.org/xml/properties/dom/document-class-name",
                    
"org.apache.xerces.dom.PSVIDocumentImpl");
            parser.setFeature(
"http://xml.org/sax/features/validation"true);
            parser.setFeature(
"http://apache.org/xml/features/validation/schema"true);
            parser.setFeature(
"http://apache.org/xml/features/validation/schema-full-checking"true);
            parser.setFeature(
"http://xml.org/sax/features/namespaces"true);
            parser.parse(
"F:/test/XML/XSD/primer.xml");
            org.w3c.dom.Document doc 
= parser.getDocument();
         org.w3c.dom.Node node 
= com.sun.org.apache.xpath.internal.XPathAPI.selectSingleNode(doc,
                    
"/purchaseOrders/purchaseOrder/shipTo/street");
            
if (node instanceof ElementPSVI) {
                System.out.println(
"****" + ((ElementPSVI) node).getNil());
            }

        }
 catch (SAXNotRecognizedException e) {
            e.printStackTrace();
        }
 catch (SAXNotSupportedException e) {
            e.printStackTrace();
        }
 catch (SAXException e) {
            e.printStackTrace();
        }
 catch (IOException e) {
            e.printStackTrace();
        }
 catch (TransformerException e) {
            e.printStackTrace();
        }

    }

}

注意:在没有配置好对应的XSD时,会出现这样的提示信息。xsi:nil也无法正常获取。
[Error] primer.xml:2:72: cvc-elt.1: Cannot find the declaration of element 'purchaseOrders'.
****false

需要创建一个primer.xsd放在对应的目录下。
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    
<xsd:annotation>
        
<xsd:documentation xml:lang="en">
   Purchase order schema 
for Example.com.
   Copyright 
2000 Example.com. All rights reserved.
  
</xsd:documentation>
    
</xsd:annotation>
    
<xsd:element name="purchaseOrders">
        
<xsd:complexType>
            
<xsd:sequence>
                
<xsd:element ref="purchaseOrder" minOccurs="0" maxOccurs="unbounded"/>
            
</xsd:sequence>
        
</xsd:complexType>
    
</xsd:element>
    
<!--xsd:element name="purchaseOrder" type="PurchaseOrderType"/-->
    
<xsd:element name="comment" type="xsd:string"/>
    
<xsd:complexType name="PurchaseOrderType">
        
<xsd:sequence>
            
<xsd:element name="shipTo" type="USAddress"/>
            
<xsd:element name="billTo" type="USAddress"/>
            
<xsd:element ref="comment" minOccurs="0"/>
            
<xsd:element name="items" type="Items"/>
        
</xsd:sequence>
        
<xsd:attribute name="orderDate" type="xsd:date"/>
        
<xsd:attribute name="id" type="xsd:string"/>
    
</xsd:complexType>
    
<xsd:complexType name="USAddress">
        
<xsd:sequence>
            
<xsd:element name="name" nillable="false">
                
<xsd:simpleType>
                    
<xsd:restriction base="xsd:string"/>
                
</xsd:simpleType>
            
</xsd:element>
            
<xsd:element name="street" type="xsd:string" nillable="true"/>
            
<xsd:element name="city" type="xsd:string"/>
            
<xsd:element name="state" type="xsd:string"/>
            
<xsd:element name="zip" type="xsd:decimal"/>
        
</xsd:sequence>
        
<xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
    
</xsd:complexType>
    
<xsd:complexType name="Items">
        
<xsd:sequence>
            
<xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
                
<xsd:complexType>
                    
<xsd:sequence>
                        
<xsd:element name="productName" type="xsd:string"/>
                        
<xsd:element name="quantity">
                            
<xsd:simpleType>
                                
<xsd:restriction base="xsd:positiveInteger">
                                    
<xsd:maxExclusive value="100"/>
                                
</xsd:restriction>
                            
</xsd:simpleType>
                        
</xsd:element>
                        
<xsd:element name="USPrice" type="xsd:decimal"/>
                        
<xsd:element ref="comment" minOccurs="0"/>
                        
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
                    
</xsd:sequence>
                    
<xsd:attribute name="partNum" type="SKU" use="required"/>
                
</xsd:complexType>
            
</xsd:element>
        
</xsd:sequence>
    
</xsd:complexType>
    
<!-- Stock Keeping Unit, a code for identifying products -->
    
<xsd:simpleType name="SKU">
        
<xsd:restriction base="xsd:string">
            
<xsd:pattern value="d{3}-[A-Z]{2}"/>
        
</xsd:restriction>
    
</xsd:simpleType>
    
<xsd:element name="purchaseOrder" type="PurchaseOrderType" nillable="true"/>
</xsd:schema>

这样运行出来的结果是:
 ****true

多谢阅读!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值