2013-11-25 32 views
0

比方說,我有一個產生這樣的XML(實際上,這是一個SharePoint項目)第三方庫:如何使用XDocument.CreateWriter方法?

<webParts> 
    <webPart xmlns="http://schemas.microsoft.com/WebPart/v3"> 
     <metaData> 
      <type name="SomeType, SomeAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ecb5ce1bdfc30252" /> 
      <importErrorMessage>Impossible d’importer ce composant WebPart.</importErrorMessage> 
     </metaData> 
     <data> 
      <properties> 
       <property name="DataFields" type="string" /> 
       <property name="XmlDefinitionLink" type="string" /> 
       <property name="FilterIncludeChildren3" type="bool">False</property> 

      </properties> 
     </data> 
    </webPart> 
</webParts> 

這個XML是通過調用一個接受XmlTextWriter參數的方法產生。因爲我想用XDocument對象的工作,我用這個代碼:

var sb = new StringBuilder(); 
using(var sw = new StringWriter(sb)) 
using (var xw = new XmlTextWriter(sw)) 
{ 
    sourceMgr.ExportWebPart(webPartToClone, xw); 
} 
var wpAsXml = XDocument.Parse(sb.ToString()); 

這是按預期工作。然而,爲了減少代碼的行數,我也試過這個代碼:

var wpAsXml = new XDocument(); 
sourceMgr.ExportWebPart(webPartToClone, wpAsXml.CreateWriter()); 

但這個代碼失敗,出現以下錯誤:

System.Xml.XmlException: The prefix '' cannot be redefined from '' to 'http://schemas.microsoft.com/WebPart/v3' within the same start element tag. 
    at System.Xml.XmlWellFormedWriter.PushNamespace(String prefix, String ns, Boolean explicitlyDefined) 
    at System.Xml.XmlWellFormedWriter.WriteEndAttribute() 
    at System.Web.UI.WebControls.WebParts.WebPartManager.ExportWebPart(WebPart webPart, XmlWriter writer) 
    at Microsoft.SharePoint.WebPartPages.SPWebPartManager.ExportWebPartInternal(WebPart webPart, XmlWriter writer) 
    at Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager.ExportWebPart(WebPart webPart, XmlWriter writer) 
    at SomeWhereInMycode 

爲什麼第二個代碼段無法正常工作?什麼是使用這種方法的正確方法?

PS:using .net 3.5 SP1

+1

我認爲這只是在XmlWellFormedWriter一個bug,這個代碼在.NET中作了大量更新4.好東西,你已經有了一個解決方法。 –

回答

0

我無法在本地重新創建場景;所以這是在黑暗中拍攝的。這可能是一個範圍問題的嘗試:

XNamespace wp = "http://schemas.microsoft.com/WebPart/v3"; 

XDocument wpAsXml = new XDocument(new XDeclaration("1.0", "utf-8", "true"), 
            new XElement(wp + "webParts"));  

using (XmlWriter writer = wpAsXml.CreateWriter()) 
{ 
    sourceMgr.ExportWebPart(webPartToClone, writer); 
} 
+0

感謝您的建議,但不幸的是,行爲完全一樣。 –

+0

@SteveB用命名空間查看新的編輯。 – OmegaMan