Torben Gott
Torben Gott

Reputation: 11

How to remove attribute name and value of a xml file?

first of all, sorry for my bad english. My problem: i have to write a script on VB.Net which should go through a xml file and search for all elements with a specific attribute name. If one is found it should remove the name and the value. The element name stays. When all is cleared the document should be saved.

My first thought to convert the whole xml (pretty big files) as string and try to do it with RegEx but i searched and saw some threads here, which convinced me not to. I saw some threads about Linq to xml and tried a few things out which didn't work.

The element names can be different.

<ph audience="1234">Randomtext</ph>
<li audience="2323">Randomtext</li>
<table audience="1234">Randomtext</table>

to

<ph>Randomtext</ph>
<li>Randomtext</li>
<table>Randomtext</table>

Would be nice if someone could help me there.

Upvotes: 1

Views: 1485

Answers (1)

Victor Zakharov
Victor Zakharov

Reputation: 26414

Here is some code for you to play with:

'instead of inline xml declaration, you can use
'XDocument.Load("path")
'or
'XDocument.Parse("xml_content")

Dim xml = <xml>
            <ph audience="1234">Randomtext</ph>
            <li audience="2323">Randomtext</li>
            <table audience="1234">Randomtext</table>
            <othernode>Randomtext</othernode>
          </xml>

Dim elements = xml.Descendants.
  Where(Function(x) x.Attribute("audience") IsNot Nothing)

For Each el As XElement In elements
  el.Attributes("audience").Remove()
Next

'xml.Save(fileName)

Console.WriteLine(xml.ToString)

Output:

enter image description here

Reference:

Upvotes: 1

Related Questions