Home > Enterprise >  Xpath in xsd schema
Xpath in xsd schema

Time:11-19

I would like name3 array to include the documentation text of the ascendant element <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>. I would like to have a generic code which prints the doccumentation according to the name of the xsd:element.

I have succeeded to include all the documentations using the xpath I provided. But I want the extra condition I mentioned to be included in the xpath.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="http://tempuri.org/PurchaseOrderSchema.xsd"
           targetNamespace="http://tempuri.org/PurchaseOrderSchema.xsd"
           elementFormDefault="qualified">
 <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>
 <xsd:complexType name="PurchaseOrderType">
         <xsd:annotation>
            <xsd:documentation xml:lang="en">
                commmennttt
            </xsd:documentation>
        </xsd:annotation>
  <xsd:sequence>
   <xsd:element name="ShipTo" type="tns:USAddress" maxOccurs="2"/>
   <xsd:element name="BillTo" type="tns:USAddress"/>
  </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:integer"/>
  </xsd:sequence>
  <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
 </xsd:complexType>
</xsd:schema>

t3 = etree.ElementTree(file='new.xsd')
name3 = t3.xpath("//xsd:documentation[text()]", namespaces={"xsd":"http://www.w3.org/2001/XMLSchema"})
name3 = [a.text for a in name3]
print(name3[0])

Thanks

CodePudding user response:

Finding the xsd:element by criteria and then by next sibling containg a xsd:documentation descendant.

from lxml import etree
crit = 'PurchaseOrder'
t3 = etree.parse('test.xsd')
ns = {"xsd":"http://www.w3.org/2001/XMLSchema"}
xpathExpr=f"//xsd:element[@name='{crit}']/following-sibling::*//xsd:documentation[text()]"
print(xpathExpr)
name3 = t3.xpath(xpathExpr, namespaces=ns)

# avoid reusing a variable for a different purpose
comments = [a.text for a in name3]
print(comments)

Result

//xsd:element[@name='PurchaseOrder']/following-sibling::*//xsd:documentation[text()]
['\n                commmennttt\n            ']
  •  Tags:  
  • xml
  • Related