Link to home
Start Free TrialLog in
Avatar of Victor  Charles
Victor CharlesFlag for United States of America

asked on

Help with removing space and "/" from dataelements using VB.NET

Hi,

If File 1 contains:

<Root>
<table>
<NSC>C 28<NSC>
<AGD>H /77<AGD>
<NSN>C/78<NSN>
<UAD>D   56<UAD>
</table>
</Root>

How do I obtain remove the spaces and "/" to obtain:

<Root>
<table>
<NSC>C28<NSC>
<AGD>H77<AGD>
<NSN>C78<NSN>
<UAD>D56<UAD>
</table>
</Root>

Thanks,

Victor
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

Dim myXmlDocument as XmlDocument = new XmlDocument()
'myXmlDocument.Load ("data.xml")
myXmlDocument.LoadXml ("<Root><table><NSC>C 28</NSC> <AGD>H /77</AGD> <NSN>C/78</NSN> <UAD>D   56</UAD> </table></Root>")

For Each node In myXmlDocument.DocumentElement.ChildNodes(0).ChildNodes

	node.InnerText = node.InnerText.Replace(" ","").Replace("/", "")

Next

'myXmlDocument.Save("data1.xml")
myXmlDocument.Dump

Open in new window

Extending the answer from MlandaT, you can also use regex:
node.InnerText = Regex.Replace(node.InnerText, " /", "" )
Hi Victor;

This should do what you need.
'' Load the XML into memory
Dim xdoc = XDocument.Load("C:\Working Directory\VictorFile3.xml")
'' Get a reference to all the Child elements of each table node
Dim results = (From n In xdoc.Descendants("table").Elements()
               Select n).ToList()
'' Remove unwanted characters
results.ForEach(Sub(n) n.Value = Regex.Replace(n.Value,"[ /]+", ""))

'' Save the modified XML to file system
xdoc.Save("Path and filename goes here")

Open in new window

Avatar of Victor  Charles

ASKER

Hi,

 How do I modify the code to only apply to one data element (i.e. NSC)

Thank you.

Victor
Use the SelectNodes method (http://www.csharp-examples.net/xml-nodes-by-name/)
Dim myXmlDocument as XmlDocument = new XmlDocument()
'myXmlDocument.Load ("data.xml")
myXmlDocument.LoadXml ("<Root><table><NSC>C 28</NSC> <AGD>H /77</AGD> <NSN>C/78</NSN> <UAD>D   56</UAD> </table></Root>")

For Each node In myXmlDocument.DocumentElement.ChildNodes(0).SelectNodes("NSC")

	node.InnerText = node.InnerText.Replace(" ","").Replace("/", "")

Next

'myXmlDocument.Save("data1.xml")
myXmlDocument.Dump

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank You, will try it and get back to you.
Thank You.
Not a problem, glad to help.