从XmlWriter获取特定的XML节点C#

时间:2018-03-05 16:46:59

标签: c# .net xml xmlreader xmlwriter

我想知道是否有可能从XmlWriter获取特定的XML节点。

我有一个方法,可以将员工导出到XML文档,并且有一个结构,如:

<header> 
<agency>
...
<employees>
 <employee>
  ....
 </employee>
 <empolyee>
  ...
 </employee>
</employees>
...

在此方法的循环中,每个员工都被创建并填充了元素。已经编写了导出此XML的整个方法。

现在,在循环结束时,我想创建一个字符串,其中包含员工的节点,但我不知道如何使用充满数据的编写器来完成在循环。

我试图寻找一些解决方案,但我没有找到任何有益于我的情况。我考虑过像MemoryStream这样的东西,但我认为你需要在创建XmlWriter时传递流,在我的情况下首先写入头节点等。

你可以帮我解决这个问题吗?我不想创建另一个Writer或Reader并编写两次节点。首先,我想找到一些更好的解决方案。

谢谢!

编辑:我可以根据需要粘贴部分代码:

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = ("\t");
        settings.OmitXmlDeclaration = false;
        XmlWriter xmlWriter = XmlWriter.Create(filenameXml, settings);

        xmlWriter.WriteStartElement("message");
        xmlWriter.WriteStartElement("data");

        xmlWriter.WriteStartElement("header");
        xmlWriter.WriteElementString("agency", agencyNumber);
        xmlWriter.WriteElementString("date", DateTime.Now.ToShortDateString());
        xmlWriter.WriteEndElement();

        xmlWriter.WriteStartElement("employees");

        //Loading of employees from DB and some other work

        for (int i = 0; i < employeesDs.RowCount(); i++)
        {                 
            xmlWriter.WriteStartElement("employee");

            //A lot of work - xmlWriter.WriteElementString so many times or WriteStartElement (address, numbers, dates etc)

            xmlWriter.WriteEndElement();   // employee

            //HERE I would like to add new method which stores whole Employee element created in this iteration i to the string
            //After that I need to store this string to DB to VARCHAR MAX, but I don't know how to get the string of the Employee
            //from the writer in this part of the code 
        }

        //another work - closing and flushing xmlwriter, disposing etc and exporting whole xml document

0 个答案:

没有答案