2009-09-04 55 views

回答

2

根據StringWriter發送變換到XmlTextWriter。然後通過從StringWriter撤回XML字符串來實例XPathDocument

var sw = new StringWriter(); 
var xtw = new XmlTextWriter(sw); 

myTransform.Transform(myXml, xtw); 

var xpd = new XPathDocument(sw.ToString()); 

它不是最高效的內存機制,但對大多數需求來說足夠了。類似的方法將使用MemoryStream而不是StringWriter,但通過比較它有點混亂。

3

瓊斯先生的回答對我非常有幫助,但是我發現最後一行不起作用。最後我做這個:

XslCompiledTransform xsl = new XslCompiledTransform(); 
xsl.Load(filePath); 
StringWriter stringWriter = new StringWriter(); 
XmlWriter xmlWriter = XmlTextWriter.Create(stringWriter); 
xsl.Transform(xPathDoc, xmlWriter); 
String newXml = stringWriter.ToString(); 
StringReader stringReader = new StringReader(newXml); 
xPathDoc = new XPathDocument(stringReader); 

(在這裏,xPathDoc是,已經從一個XmlReader初始化的XPathDocument中。)

2

稍微好一點的大衛·安德森的回答的形式是以下:它不遭受潛在的資源泄漏;否則它是一樣的。

private static XPathDocument TransformToXPathDocument(string styleSheetPath, 
                 IXPathNavigable xPathDoc) 
{ 
    var xsl = new XslCompiledTransform(); 
    xsl.Load(styleSheetPath); 
    using(var stringWriter = new StringWriter()) 
    { 
     using(XmlWriter xmlWriter = XmlWriter.Create(stringWriter)) 
     { 
      xsl.Transform(xPathDoc, xmlWriter); 
     } 
     using(var reader = new StringReader(stringWriter.ToString())) 
     { 
      return new XPathDocument(reader); 
     } 
    } 
} 
相關問題