输入 XML:
<foobar>
<Comments>
Reported By: L & A Q TESTING, TESTED
Date of TESTING: Available
TESTING unavailable to resolve Test issue.
Additional Comments: Comments
Had to go into Testing System and change to the correct notification group. Per sup.
</Comments>
</foobar>
XSLT 代码:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output indent="no" omit-xml-declaration="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space()" />
</xsl:template>
<xsl:template match="text()[../*]"/>
</xsl:stylesheet>
预期输出:
<foobar><Comments>Reported By: L & A Q TESTING, TESTED Date of TESTING: Available TESTING unavailable to resolve Test issue. Additional Comments: Comments Had to go into Testing System and change to the correct notification group. Per sup.</Comments></foobar>
我得到了什么:
<foobar>
<Comments>Reported By: L & A Q TESTING, TESTED Date of TESTING: Available TESTING unavailable to resolve Test issue. Additional Comments: Comments Had to go into Testing System and change to the correct notification group. Per sup.</Comments>
</foobar>
观察:
尽管 text() 节点中不必要的空格已得到纠正.. 输出 XML 中仍然存在缩进。
理想情况下strip-space
应该照顾它..在它之上我添加了下面的代码
<xsl:template match="text()[../*]"/>
还是没有运气!!的使用
XPathDocument xpathXmlOrig = new XPathDocument(string_xmlInput);
在我的 C# 代码错误中说 .. strip-space cannot be applied to document which has been loaded!! 所以我正在使用 XMLReader ..
添加 C# 代码以供参考..
XslCompiledTransform xslTransform = new XslCompiledTransform();
string xslinput = "<?xml version=\"1.0\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:strip-space elements=\"*\"/><xsl:output indent=\"no\" omit-xml-declaration=\"yes\"/><xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template><xsl:template match=\"text()[not(../*)]\"><xsl:value-of select=\"normalize-space()\" /></xsl:template><xsl:template match=\"text()[../*]\"/></xsl:stylesheet>";
string strXmlOutput = string.Empty;
StringWriter swXmlOutput = null;
MemoryStream objMemoryStream = null;
swXmlOutput = new StringWriter();
objMemoryStream = new MemoryStream();
UTC_Calc obj = new UTC_Calc();
XsltArgumentList xslArg = new XsltArgumentList();
..........
........
XmlReader reader = XmlReader.Create(string_xmlInput, settings);
XsltSettings xslsettings = new XsltSettings(false, true);
MemoryStream memStream = new MemoryStream();
XmlReader rd = XmlReader.Create(new StringReader(xslinput));
xslTransform.Load(rd);
xslTransform.Transform(reader, xslArg, objMemoryStream);
objMemoryStream.Position = 0;
StreamReader objStreamReader = new StreamReader(objMemoryStream);
strXmlOutput = objStreamReader.ReadToEnd();
..........
........
XmlDocument outputxml = new XmlDocument();
outputxml.LoadXml(strXmlOutput);
outputxml.Save(outputfile.FileName);