Home > Back-end >  Convert element into its value in XML C#
Convert element into its value in XML C#

Time:03-18

I have an array in my xml:

Existing XML

<data>
  <item name="item1">test1</item>
  <item name="item2">test2</item>
  <item name="item3">test3</item>
</data>

What I expect is:

<data>
  <item1>test1</item>
  <item2>test2</item>
  <item3>test3</item>
</data>

I am using XmlDocument in C#

var xml = new XmlDocument();
xml.loadXml(myjson string)
...

Where my xml is my Exsting Xml above. How can I achieve this?

Thanks

CodePudding user response:

Assuming that:

  • You're happy to use LINQ to XML
  • You only have a single level of elements

... then it's quite straightforward:

using System;
using System.Linq;
using System.Xml.Linq;

var doc = XDocument.Load("test.xml");

foreach (var element in doc.Root.Elements().ToList())
{
    element.ReplaceWith(new XElement(element.Attribute("name").Value, element.Value));
}

Console.WriteLine(doc);

Using XNode.ReplaceWith is only one option, of course - you could easily create a new doc instead, e.g.

using System;
using System.Linq;
using System.Xml.Linq;

var doc = XDocument.Load("test.xml");

var elements = doc.Root
    .Elements()
    .Select(x => new XElement(x.Attribute("name").Value, x.Value));

var newDoc = new XDocument(new XElement("data", elements));
Console.WriteLine(newDoc);

CodePudding user response:

For comparison, the XSLT solution is

<data xmlns:xsl="http://www.w3.org/1999/XSL/Transform version="1.0">
  <xsl:for-each select="data/*">
    <xsl:element name="{@name}">
      <xsl:copy-of select="node()"/>
    </xsl:element>
  </xsl:for-each>
</data>

CodePudding user response:

try this

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(annotationsxml);
    XmlNode node = xmlDoc.SelectSingleNode("data");

    var doc = new XmlDocument();
    XmlElement usersNode = doc.CreateElement("data");
    doc.AppendChild(usersNode);
    foreach (XmlNode xn in node)
    {
        XmlElement userEl = doc.CreateElement(xn.Attributes[0].Value);
        userEl.InnerText = xn.InnerText;
        usersNode.AppendChild(userEl);
    }

result

<data>
   <item1>test1</item1>
   <item2>test2</item2>
   <item3>test3</item3>
</data>

CodePudding user response:

Here is an XElement approach:

XElement doc = XElement.Load("path to file");
    var results = doc.Descendants();//if not single level you can add your node name here like .Desendants("data")
    results.Attributes().Remove();
    int count = 1;
    foreach(XElement ele in results)
      {
         ele.Name = ele.Name   count.ToString();
         count  ;
      }    
    doc.Save("path to file");
  • Related