将XmlNode添加到XmlWriter

本文关键字:XmlWriter 添加 XmlNode | 更新日期: 2023-09-27 18:03:37

我有一些xml节点,我已经拉出来,我使用XmlWriter来创建相关的xml文件。

XmlNode需要进入内部,但我不确定如何使用XmlNode来创建内部的元素。

Xml格式如下

<?xml version="1.0" encoding="UTF-8"?>
<tasks>
   <task Id="113" Date="2013-03-12T13:55:09" NodeId="1842" TotalWords="11">
   </task>
</tasks>

XmlWriter代码

using (XmlWriter writer = XmlWriter.Create(MapPath(xmlFilePath)))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Tasks");
                    writer.WriteStartElement("Task");
                    writer.WriteAttributeString("Id", t.Id.ToString());
                    writer.WriteAttributeString("NodeId", t.Node.Id.ToString());
                    // The XmlNode needs to be inside here //
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndDocument();

                }

我取出的XmlNode的详细信息

<Page id="1842" parentID="1840" level="5" writerID="14" creatorID="14" nodeType="1051" template="1839" sortOrder="0" createDate="2013-03-11T14:53:47" updateDate="2013-03-12T14:03:55" nodeName="Ujian sub-halaman" urlName="ujian-sub-halaman" writerName="John John" creatorName="John John" path="-1,1057,1631,1156,1840,1842" isDoc="">
         <pageContent />
         <heroHeaderImage />
         <topModule>-1</topModule>
         <bottomModule>-1</bottomModule>
         <rHTopModule />
         <headerQuickLinks>
            <data />
         </headerQuickLinks>
         <rHBottomModule>-1</rHBottomModule>
         <pageTitle>Ujian sub-halaman</pageTitle>
         <umbracoNaviHide>0</umbracoNaviHide>
         <pageHeader><![CDATA[Test sub-page]]></pageHeader>
         <showAddThis>0</showAddThis>
         <alternativeTitle>Test sub-page</alternativeTitle>
         <smallPrint>0</smallPrint>
         <pageImage />
         <siteName />
         <metaDescription />
         <metaKeywords />
         <metaCopyright />
         <defaultEmail />
         <googleUrchin />
         <facebook />
         <googlePlus />
         <linkedIn />
         <twitter />
         <youtube />
      </Page>

将XmlNode添加到XmlWriter

我不确定这是否是您的意思,但假设您有一个XmlNode -让我们称之为the_node,那么您可以使用XmlWriter的WriteRaw方法将节点的标记嵌入到writer的输出流中。

using (XmlWriter writer = XmlWriter.Create(MapPath(xmlFilePath)))
{
   writer.WriteStartDocument();
   writer.WriteStartElement("Tasks");
   writer.WriteStartElement("Task");
   writer.WriteAttributeString("Id", t.Id.ToString());
   writer.WriteAttributeString("NodeId", t.Node.Id.ToString());
  // The XmlNode needs to be inside here //
   writer.WriteRaw(the_node.OuterXml);
   writer.WriteEndElement();
   writer.WriteEndElement();
   writer.WriteEndDocument();

}