简体   繁体   中英

XmlDocument rearrange XmlNodes C#

I have an XML Document that stores all sorts of information about users of a system. Utlimately, the nodes that I am intersted in I hae outined below.

So, there is a user that has many user contents - I have included just books as an example.

<?xml version="1.0" encoding="UTF-8"?>
<user>
  <userProperties>
    <alias val="userAliasOne"/>
    <id val="3423423"/>
  </userProperties>
  <userContent>
    <userBooks>
      <genre>
        <book>
          <title>Dummy Value</title>
        </book>
      </genre>
    </userBooks>
  </userContent>
</user>

I need to somehow restructure the XML, using XmlDocument and XmlNode so that it matches the below. (userBooks to become root node but all contents of userBooks - /genre/book/title - to stay inside userContent).

<?xml version="1.0" encoding="UTF-8"?>
<userBooks>
  <user>
    <userProperties>
      <alias val="userAliasOne"/>
      <id val="3423423"/>
    </userProperties>
    <userContent>
      <genre>
        <book>
          <title>Dummy Value</title>
        </book>
      </genre>
    </userContent>
  </user>
</userBooks>

I've tried selecting the single nodes and cloning them, then appending the clone to the parent and removing the child that's no longer required. It became very long and convoluted and I couldn't get it to work. There must be a more elegant solution that I am not aware of.

Any help appreciated.

Thanks.

Here's an example for adding a new root element:

using System;
using System.Xml;

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("test.xml");
        var originalRoot = doc.DocumentElement;
        doc.RemoveChild(originalRoot);
        var newRoot = doc.CreateElement("userBooks");
        doc.AppendChild(newRoot);
        newRoot.AppendChild(originalRoot);
        doc.Save(Console.Out);
    }
}

Try using the same approach for "removing" the userBooks element in the original - remove the element from its parent, but then add all the child nodes (of userBooks ) as new child nodes of the original parent of userBooks .

Using XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> userBooks = doc.Descendants("userBooks").ToList();

            foreach(XElement userBook in userBooks)
            {
                userBook.ReplaceWith(userBook.Element("genre"));
            }
        }
    }
}
​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM