Remove All Attributes from XML using csharp?

Veggies

New member
Joined
Jul 3, 2022
Messages
3
Programming Experience
5-10
I have Tried to remove all the attributes from XML but getting some errors please help me to achieve my result.

C sharp code:
var strData=@"
<data>
<emp_details id="5" grade="z0234-o0948-45op-0002">
<name>Randee Mozos</name>
<salary include="unpaid">345643</salary>
</emp_details>
<emp_details id="23" grade="z0124-o0921-41ds-0451">
<name>Nirzosha</name>
<salary include="unpaid" leave="accept">453011</salary>
</emp_details>
</data>
";



 foreach (XmlNode xmlNode in doc.SelectNodes("//ENVELOPE"))
                    {
                        RemoveAttributes(xmlNode);//error
                       
                        response = JsonConvert.SerializeObject(xmlNode);
                        _xmlREsponseList.Add(response);
                    }




 private void RemoveAttributes(XmlNode node)
        {
            string strType = node.NodeType.ToString();
            if (strType == "Element")
            {
                node.Attributes.RemoveAll();
            }
            if (node.HasChildNodes)
            {
                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    RemoveAttributes(node.ChildNodes[i]);
                }
            }
        }


desire output:
C#:
{
  "data": {
    "emp_details": [
      {
        "name": "Randee Mozos",
        "salary": 345643
      },
      {
        "name": "Nirzosha",
        "salary": 453011
      }
    ]
  }
}
 
Last edited by a moderator:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,469
Location
Chesapeake, VA
Programming Experience
10+
getting some errors
What errors are you getting?

Also your desired put looks like JSON. Removing XML attributes does not given you JSON. Removing XML attributes will still give you XML with just tagnames and data. It will still be XML.
 
Last edited:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,469
Location
Chesapeake, VA
Programming Experience
10+
I had errors in your code, but it was on lines 1-12 due to the unescaped quotes. And then another error on lines 16, 20, and 21 due to undeclared variables.

And then there's two logic errors. First on line 16 where you are looking for the "ENVELOPE" element, but your data has no envelope, so the loop will not actually do anything. Second is your attempt to serialize each node within loop.

After overcoming all those issues, I got this:
Screenshot_1.png
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,469
Location
Chesapeake, VA
Programming Experience
10+
You still did not state what error you were getting.
 
Top Bottom