比方說,我有一個產生這樣的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
我認爲這只是在XmlWellFormedWriter一個bug,這個代碼在.NET中作了大量更新4.好東西,你已經有了一個解決方法。 –