ag112
ag112

Reputation: 5697

how to fetch content of xml element using idref

I have a XML schema:-

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  elementFormDefault="unqualified">

 <xsd:element name="Person">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="Name" type="xsd:string"/>
         </xsd:sequence>
         <xsd:attribute name="id" type="xsd:ID" use="required"/>
      </xsd:complexType>
   </xsd:element>

   <xsd:element name="Book">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="Title" type="xsd:string"/>
            <xsd:element name="Author">
               <xsd:complexType>
                  <xsd:attribute name="idref" type="xsd:IDREF" 
                                 use="required"/>
               </xsd:complexType>
            </xsd:element>
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>

<xsd:element name="root">
    <xsd:complexType>
         <xsd:sequence>
                <xsd:element  ref="Person" />
                <xsd:element  ref="Book" />
         </xsd:sequence>
  </xsd:complexType>       
</xsd:element>

</xsd:schema>

and corresponding to above XML schema, I have following incoming XML:-

<?xml version="1.0" encoding="utf-8" ?> 
<root>

  <Person id="P234">
      <Name>0002</Name>
    </Person> 
<Book>
     <Title>0001</Title>
    <Author idref="P234"/>
    </Book>

 </root>

I know using XML parser validation, I can validate if above XML conforms to my XML schema.for e.g. id and idref should be present. Now what I want to know is which parser(SAX/DOM/STAX) can fetch me complete XML element based on idref. So basically in above example, once parser reaches idref="P234", it should return me complete <Person>...</Person>. Another query is does any parser support id and idref merging, which can replace content of idref with actual element and return me merged XML.

Upvotes: 1

Views: 1483

Answers (1)

kan
kan

Reputation: 28971

Parsers don't do it, as I know. Use XSLT to do the magic. Moreover, idrefs could be self-referenced, have a cyclic dependency, so it's impossible just "replace content with actual element".

E.g. say you have the xml:

<?xml version="1.0" encoding="utf-8" ?> 
<root>
    <Person id="P234">
        <Name>0002</Name>
        <WroteBook idref="B442"/>
    </Person> 
    <Book id="B442">
        <Title>0001</Title>
        <Author idref="P234"/>
    </Book>
</root>

What would you expect from a parser?

An XSLT (not tested myself however):

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="@idref">
            <xsl:apply-templates select="id(.)"/>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 2

Related Questions