如何动态地将元素附加到xml文档?

时间:2018-04-11 06:29:44

标签: c# xmltextwriter

根据以下代码,我创建了xml文件并迭代地写入它。但问题是它是覆盖文件。我想将新元素追加到文件中,这里foreach迭代地将wrobj的内容写入xml,但是再次覆盖

XmlTextWriter xtWriter = new XmlTextWriter("demoxml.xml",Encoding.UTF8);
xtWriter.Formatting = System.Xml.Formatting.Indented;
xtWriter.WriteStartElement("Selected-Workspace");
xtWriter.WriteStartElement("Context-Details");

xtWriter.WriteStartElement("Conid");
xtWriter.WriteString(it.id);
xtWriter.WriteEndElement();

xtWriter.WriteStartElement("Attributes"); //attributes started

xtWriter.WriteStartElement("name");
xtWriter.WriteString(it.attributes.name);
xtWriter.WriteEndElement();
xtWriter.WriteStartElement("organizationReference");
xtWriter.WriteString(it.attributes.organizationReference);
xtWriter.WriteEndElement();
xtWriter.WriteStartElement("organizationReferenceName");
xtWriter.WriteString(it.attributes.organizationReference_name);
xtWriter.WriteEndElement();
xtWriter.WriteStartElement("type");
xtWriter.WriteString(it.attributes.type);
xtWriter.WriteEndElement();

xtWriter.WriteEndElement();// End Attributes
foreach (WorkspaceRootObject wro in wrObj) 
{
    xtWriter.WriteStartElement("Workspace-Details"); // Workspace start

    xtWriter.WriteStartElement("WorkspaceId");
    xtWriter.WriteString(wro.id);
    xtWriter.WriteEndElement();
    xtWriter.WriteStartElement("name");
    xtWriter.WriteString(wro.name);
    xtWriter.WriteEndElement();
    xtWriter.WriteStartElement("description");
    xtWriter.WriteString(wro.description);
    xtWriter.WriteEndElement();
    xtWriter.WriteStartElement("context-id");
    xtWriter.WriteString(wro.contextId);
    xtWriter.WriteEndElement();

    xtWriter.WriteEndElement(); //End Workspace
}

xtWriter.WriteEndElement();
xtWriter.WriteEndElement();
xtWriter.Flush();
xtWriter.Close();

如何将wrobj对象的内容追加到文件中。

1 个答案:

答案 0 :(得分:0)

第一次创建文件时,请执行上述操作。下一次,检查文件是否存在,并使用XDocument追加here

中给出的内容