。如果该节点(贡献者)有子节点,则.Net XSLT解析器无法识别父属性(类型)。对于以下场景返回空,但如果删除子节点则返回正确的结果。
输入XML
<contributors>
<roles>
<role type="Actor">
<contributor />
</role>
</roles>
</contributors>
XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/">
<a>
<xsl:value-of select="contributors/roles/role/@type" />
</a>
</xsl:template>
</xsl:stylesheet>
输出
<a></a>
我的C#方法
public static XDocument TransformXML(string inputXMLString, string xslt)
{
var xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(inputXMLString));
inputXMLString = xmlDocumentWithoutNs.ToString();
var xslCompiledTransform = new XslCompiledTransform();
using (var stringReader = new StringReader(xslt))
using (var xmlReader = XmlReader.Create(stringReader))
{
xslCompiledTransform.Load(xmlReader);
}
using (var stringReader = new StringReader(inputXMLString))
using (var xmlReader = XmlReader.Create(stringReader))
using (var stringWriter = new StringWriter())
{
xslCompiledTransform.Transform(xmlReader, new XsltArgumentList(), stringWriter);
var resultXML = stringWriter.ToString();
var otuput = XDocument.Parse(resultXML);
return otuput;
}
}
答案 0 :(得分:1)
尝试不删除NS。它为我工作: - )
var xmlDocumentWithoutNs = XElement.Parse(inputXMLString);