简体   繁体   中英

Using XSLT to Transform into XML

Trying to figure out why this is not working. I have followed the instructions on W3Schools XSLT Docs and as well W3Schools XPath Docs and I keep on getting null for the "MeterNo" value of the "MeterInfo" tag.

XSLT

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
                exclude-result-prefixes="msxsl">

<xsl:template match="/">
  <MeterInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <MeterNo>
      <xsl:value-of select="Template[@name='MyTemplateName']/Field[@name='MyFieldName']"/>
    </MeterNo>
  </MeterInfo>
</xsl:template>

XML

<?xml version="1.0" encoding="utf-8"?>
<ProcessHostRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
                    xmlns="http://www.utilitysolutions.cgi.com/UHIB-1_0">
   <DataArea>
      <Process xmlns="http://www.openapplications.org/oagis" />
      <HostRequest>
         <Template name="MyTemplateName">
            <Field name="MyFieldName">
               8768565
            </Field>
         </Template>
      </HostRequest>
   </DataArea>
</ProcessHostRequest>

My Transformation Response

<?xml version="1.0" encoding="UTF-8"?>
<MeterInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <MeterNo/>
</MeterInfo>

Two errors:

First in your template with match pattern / the context node is the root node. The expression select="Template[..." would only return a non-empty result if the document node would have name Template but it is ProcessHostRequest .

Therefore match for the descendant: select="//Template... .

Second the Template and Field elements are in namespace http://www.utilitysolutions.cgi.com/UHIB-1_0 . To select them you need to declare the same namespace in your XSLT:

<xsl:stylesheet version="1.0" 
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
            xmlns:c="http://www.utilitysolutions.cgi.com/UHIB-1_0"
            exclude-result-prefixes="msxsl c">

and use it accordingly

<xsl:value-of select="//c:Template[@name='MyTemplateName']/c:Field[@name='MyFieldName']"/>

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