Copying xml file with inserting new elements at a specific location - C #

Hi I want to copy xml file and paste some more elements into a specific locaiton element; What is the best and easiest way to do this. I can use the xmlReader to read the elements and write one by one, referencing each type - I had some problems with this, but also it seems to me that there is too much work to do, which could be better somehow. in below example i have xml as default definition, need to create new xml in same format with new values ​​introduced in sheet1 but after existing rows and do the same for sheet2.

<book>
   <Sheet ss:name="Sheet1">
      <Table >
      <Row >
        <Cell/>
        <Cell>
             Title Name      
        </Cell>
        <Cell >
             Title Description
         </Cell>
      </Row>
   </Sheet>
<a/>
<b/>
  <Sheet ss:name="Sheet2">
      <Table >
      <Row >
        <Cell/>
        <Cell>
             Title Name      
        </Cell>
        <Cell >
             Title Description
         </Cell>
      </Row>
   </Sheet>
</book>

      

+2


a source to share


1 answer


The easiest way is to load the entire document using LINQ to XML, modify it, and then save it again. This will most likely be easier than using XmlReader

, which can get somewhat hairy in my experience.

However, this has to do with loading it all into memory - which can be a problem if the documents are huge. Perhaps this is the problem?

EDIT: Here's a short example in LINQ to XML (untested):



XDocument doc = XDocument.Load("test.xml");
XNamespace ss = "http://url/for/ss";
Sheet sheet1 = doc.Descendants("Sheet")
                  .Where(x => (string) x.Attribute(ss + "name") == "Sheet1");
XElement lastRow = sheet1.Elements("Row").LastOrDefault();
// Note: if there aren't any rows, lastRow will be null here. Handle accordingly
lastRow.AddAfterSelf(new XElement("Foo", "Extra value"));

      

An alternative to the last part, if you just want new content after all old sheet content:

sheet1.Add(new XElement("Foo", "Extra value"));

      

+7


a source







All Articles