我需要提取根元素名称属性我的输入如下
<?xml version = '1.0' encoding = 'UTF-8'?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:nxsd="http://xmlns" nxsd:encoding="US-ASCII">
<xsd:element name="car">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="wheel" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:annotation>
<xsd:appinfo>NXSDSAMPLE=</xsd:appinfo>
<xsd:appinfo>USEHEADER=false</xsd:appinfo>
</xsd:annotation>
</xsd:schema>
XSL如下所示
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="/*/*[local-name()='element']">
<xsl:value-of select="@name"></xsl:value-of>
</xsl:template>
</xsl:stylesheet>
所需输出仅为“car”,但转换正在生成
NXSDSAMPLE=
USEHEADER=false
car
我的程序如下所示
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
StringWriter sw = new StringWriter();
File rootNameStyleSheet = new File("RootElementNameExtractor.xsl");
File datafile = new File("cf1.xsd");
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(datafile);
TransformerFactory tFactory = TransformerFactory.newInstance();
StreamSource stylesource = new StreamSource(rootNameStyleSheet);
Transformer transformer = tFactory.newTransformer(stylesource);
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, indent);
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
}
任何有关XSL错误的输入都会有所帮助
答案 0 :(得分:1)
有内置模板可确保处理从根节点开始,然后将更多模板应用于子节点。这样,您的模板最终会被使用,但您的其他输入节点也会通过内置模板进行处理。
您有两个选项,可以添加
<xsl:template match="/">
<xsl:apply-templates select="xsd:schema/xsd:element"/>
</xsl:template>
(假设您的样式表声明xmlns:xsd="http://www.w3.org/2001/XMLSchema"
)或确保使用
<xsl:template match="text()"/>
答案 1 :(得分:1)
我会写一个简单的样式表
<xsl:template match="/">
<xsl:value-of select="/*/xsd:element[1]/@name"/>
</xsl:template>