在这篇文章的 PS 中,您可以找到一个 C# 代码片段,它使用 XSLT 转换 + RegEx 匹配从 XML 文档中获取货币汇率值。请阅读我的问题内联引用
//+
...
//-
注释行组。
谢谢你。
PS代码:
string currencyCode = "RUB";
var xml = new StringReader(
@"<gesmes:Envelope
xmlns:gesmes='http://www.gesmes.org/xml/2002-08-01'
xmlns{{EmptyNameSpace}} ='http://www.ecb.int/vocabulary/2002-08-01/eurofxref'>
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time='2012-06-27'>
<Cube currency='USD' rate='1.2478' />
<Cube currency='RUB' rate='41.1252' />
<Cube currency='ZAR' rate='10.4601' />
</Cube>
</Cube>
</gesmes:Envelope>"
.Replace("{{EmptyNameSpace}}", ":ns1")
//+
// I'd like to get this code working the same way as it does now
// producing
//
// Result: EUR/RUB => 41.1252
//
// output but when the above code line will be commented
// and the below code line uncommented
//-
//.Replace("{{EmptyNameSpace}}", "")
);
var xslt = new XmlTextReader(new StringReader(
@"<xsl:stylesheet version='2.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:gesmes='http://www.gesmes.org/xml/2002-08-01'
xmlns:ns1 ='http://www.ecb.int/vocabulary/2002-08-01/eurofxref'
>
<xsl:variable name='x1' select='gesmes:Envelope/Cube/Cube/Cube[@currency=""{0}""]' />
<xsl:template match='gesmes:Envelope'>
[<xsl:apply-templates select='$x1' />]
</xsl:template>
<xsl:template match='Cube'>
<xsl:value-of select='@rate' />
</xsl:template>
</xsl:stylesheet>".Replace("{0}", currencyCode)
));
var xDoc = new XPathDocument(xml);
var xTr = new System.Xml.Xsl.XslCompiledTransform();
xTr.Load(xslt) ;
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
xTr.Transform(xDoc, null, writer);
string pattern = @"\[(?'name'[0-9]*\.[0-9]*)\]";
System.Console.WriteLine(
"Result: EUR/{0} => {1}",
currencyCode,
Regex.Match(sb.ToString(), pattern)
.Groups["name"].Value);
// Result: EUR/RUB => 41.1252