开发者

Validate XML Schema with xsd file in Cocoa?

I have some XML and an XML Schema in a local xsd file. The XML document does not contain any schema information. I want to validate the XML document against the xsd schema file in Cocoa (meaning I'd prefer something NS/CF/libxml based as opposed to an external library).

I can across xmllint, 开发者_如何学运维which would probably work, but I was looking for a way to do it without launching an external task.


If your xml document does not have a reference to the xml schema, you should add it yourself, then validate with NSXMLDocument validateAndReturnError: method.

Here is an example of how to tweak the xml document to have a reference to the xsd. Obviously, you will have to adapt this code to have a reference to your local xsd file.

NSError *error = nil;
NSURL *xmlURL = [NSURL URLWithString:@"http://www.xmlschema.info/PO.xml"];

NSXMLDocument *document = [[NSXMLDocument alloc] initWithContentsOfURL:xmlURL options:NSXMLNodeOptionsNone error:NULL];

NSXMLNode *noNamespaceSchemaLocation = [NSXMLNode attributeWithName:@"xsi:noNamespaceSchemaLocation" stringValue:@"http://www.xmlschema.info/PO.xsd"];
NSXMLElement *rootElement = [document rootElement]; 
NSMutableArray *rootAttributes = [[rootElement attributes] mutableCopy];
[rootAttributes replaceObjectAtIndex:1 withObject:noNamespaceSchemaLocation];
[rootElement setAttributes:rootAttributes];

BOOL isValid = [document validateAndReturnError:&error];

if (isValid)
    NSLog(@"document is valid");
else
    NSLog(@"document is invalid: %@", [error localizedDescription]);

For reference:

Contents of http://www.xmlschema.info/PO.xml

<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\microsite_images\po.xsd">
    <shipTo country="US">
        <name>Alice Smith</name>
        <street>123 Maple Street</street>
        <city>Mill Valley</city>
        <state>CA</state>
        <zip>90952</zip>
    </shipTo>
    <billTo country="US">
        <name>Robert Smith</name>
        <street>8 Oak Avenue</street>
        <city>Old Town</city>
        <state>PA</state>
        <zip>95819</zip>
    </billTo>
    <comment>Hurry, my lawn is going wild</comment>
    <items>
        <item partNum="872-AA">
            <productName>Lawnmower</productName>
            <quantity>1</quantity>
            <USPrice>148.95</USPrice>
            <comment>Confirm this is electric</comment>
        </item>
        <item partNum="926-AA">
            <productName>Baby Monitor</productName>
            <quantity>1</quantity>
            <USPrice>39.98</USPrice>
            <shipDate>1999-05-21</shipDate>
        </item>
    </items>
</purchaseOrder>

Contents of http://www.xmlschema.info/PO.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="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:complexType>

  <xsd:complexType name="USAddress">
    <xsd:sequence>
      <xsd:element name="name"   type="xsd:string"/>
      <xsd:element name="street" type="xsd:string"/>
      <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:schema>


Well, xmllint is one of the libxml tools. The XSD validation part of xmllint is simply a small wrapper around the schema module of libxml - you can see the API here. I've used this from Cocoa myself.


Newt is correct. I have some open source Cocoa code that uses the libxml XSD API.

The project is here:

http://code.google.com/p/cocoatron/

Specifically this method:

- (void)doXSDValidation:(xmlDocPtr)source;

In this file:

http://code.google.com/p/cocoatron/source/browse/trunk/ValidateXMLDocuments/Validate%20XML%20Documents.m

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜