如何使用XDocument.CreateWriter方法?

时间:2013-11-25 20:20:31

标签: c# xml

假设我有一个像这样生成xml的第三方库(实际上,这是一个SharePoint项目):

<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>

通过调用接受XmlTextWriter参数的方法生成此xml。由于我想使用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:使用.net 3.5 SP1

1 个答案:

答案 0 :(得分: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);
}