XSLT + C#:<root>由于 XmlDocument 的格式良好限制,返回没有周围帮助元素的平面节点集?



我的XSLT样式表中有一个类似的C#函数:

<xsl:stylesheet ...
xmlns:utils="urn:local">
<msxsl:script language="CSharp" implements-prefix="utils">
<![CDATA[
public XmlDocument dateSplit(string str)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement(string.Empty, "root", string.Empty);
Regex rgx = new Regex("(?:(\d{1,2})\.(\d{1,2})\.)?(\d{4})?");
Match match = rgx.Match(str);
XmlElement yearElem = doc.CreateElement(string.Empty, "year", string.Empty);
XmlElement monthElem = doc.CreateElement(string.Empty, "month", string.Empty);
XmlElement dayElem = doc.CreateElement(string.Empty, "day", string.Empty);
if (match.Success) {
string dayVal = match.Groups[1].Value;
string monthVal = match.Groups[2].Value;
string yearVal = match.Groups[3].Value;
if (dayVal != "" && monthVal != "" && yearVal != "") {
XmlText dayText = doc.CreateTextNode(dayVal.PadLeft(2, '0'));
XmlText monthText = doc.CreateTextNode(monthVal.PadLeft(2, '0'));
XmlText yearText = doc.CreateTextNode(yearVal);
dayElem.AppendChild(dayText);
monthElem.AppendChild(monthText);
yearElem.AppendChild(yearText);
} else if (yearVal != "") {
XmlText yearText = doc.CreateTextNode(yearVal);
yearElem.AppendChild(yearText);
}
}
root.AppendChild(yearElem);
root.AppendChild(monthElem);
root.AppendChild(dayElem);
doc.AppendChild(root);
return doc;
}
]]>
</msxsl:script>

它将"1960"变成<year>1960</year>,将"4.7.2016"变成<year>2016</year><month>07</month><day>04</day>

为了将元素yearmonthdayflat添加到我的输出XML中。。。

<someOtherStuff>...</someOtherStuff>
<year>2016</year>
<month>07</month>
<day>04</day>
<moreStuff>...</moreStuff>

我必须使用这样的功能:

<xsl:copy-of select="utils:dateSplit(myInput)/root/*"/>

我无法避免dateSplit()函数中的辅助<root>元素,因为XmlDocument必须是良好的形式(只有顶层的单个元素)。不可能将多个元素附加到根。

是否有一种替代方案,如ResultTreeFragment,不能确保格式良好,以避免人为和临时的<root>元素?

如果使用CreateDocumentFragment创建XmlDocumentFragment,则可以将元素添加到该片段并返回它,而不是XmlDocument:

<msxsl:script language="CSharp" implements-prefix="utils">
<![CDATA[
public XmlDocumentFragment dateSplit(string str)
{
XmlDocument doc = new XmlDocument();
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
// ...
docFrag.AppendChild(yearElem);
docFrag.AppendChild(monthElem);
docFrag.AppendChild(dayElem);
return docFrag;

然后像这样使用:

<xsl:copy-of select="utils:dateSplit(myInput)"/>