简体   繁体   中英

How to reference XML root node generically

I have some XML that looks like this;

<Root attr1="ABC">
    <Element1>
        <Element2>
             <Element3 />    
        </Element2>
        <Element2>
             <Element3 />    
        </Element2>
    <Element1>
</Root>

I have some XSLT that processes this, and for one reason or another it references the Root node as 'Root' (without quotes).

I am now in a position where I will have some identically structured XML, except the Root node is called for example. I don't want two versions of my XSLT, so can I reference the root node in a more generic fashion.

As an example of what I mean...

<xsl:when  test="/Root/@attr1 = 'ABC'">

I need this to also work for

<xsl:when  test="/NewRoot/@attr1 = 'ABC'">

I have noted in my reading on the subject that care needs to be taken to ensure the reference is the root node, and not the Document element, that latter I assume is this part of the XML

<?xml version="1.0" encoding="UTF-8"?>

Any help is as ever appreciated.

Thanks

can I reference the root node in a more generic fashion ?

Just use :

/*/@attr1 = 'ABC'

this produces true() exactly when the top element (regardless of its name) of the XML document has an attribute named attr1 , whose string value is the string: "ABC".

Here we are using the fact that a well-formed XML document must have exactly one top element -- therefore we don't need to write: /*[1]

I would suggest to use eg

<xsl:template match="/Root | /NewRoot">
  <xsl:if test="@attr1 = 'ABC'">...</xsl:if>
</xsl:template>

or perhaps it might even be better to put the attribute check into a template match pattern as well eg

    <xsl:template match="/Root | /NewRoot">
      <xsl:apply-templates select="@*"/>
    </xsl:template>

<xsl:template match="/Root/@attr1[. = 'ABC'] | /NewRoot/@attr1[. = 'ABC']">
  <!-- now output here what you want to output if the condition is met -->
</xsl:template>

If you really need to use an xsl:when test with a full path then use test="/Root/@attr1 = 'ABC' or /NewRoot/@attr1 = 'ABC'" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM