Help with removing duplicates in string using VB.NET

vcharles
vcharles used Ask the Experts™
on
Hi,

I have an xml file which contains a data element with string of duplicate data.For example<CTRY>BEL,BEL,GRC,GRC,USA<CTRY>. How do I remove the duplicate data?

For example:

<Root>
<Table>
<Id>1</id>
<ctry>BEL,BEL,GRC,GRC,USA<CTRY</ctry>
<Item>BMW</item>
</Table>
<Table>
<Id>1</id>
<ctry>BEL,BEL,GRC,GRC,USA,USA<CTRY</ctry>
<Item>BMW</item>
</Table>
<Table>
<Id>1</id>
<ctry>BEL,DEU,GRC,BEL,USA<CTRY</ctry>
<Item>BMW</item>
</Table>
</Root>

Thanks,

Victor
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
XmlDoc.DocumentElement("ctry").InnerText =
string.Join(",", XmlDoc.DocumentElement("ctry").InnerText.Split(',').Distinct().ToArray());

Commented:
not sure how you are parsing the xml but the idea is as ollows
dim duplicateString as string
duplicateString= "BEL,BEL,GRC,GRC,USA";

Dim cleanString as string = string.Join(",", duplicateString.Split(',').Distinct().ToArray())

Author

Commented:
H

Once i load the file using xmldocument how do i use your code and save the changes?

Thanks.
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Retired
Distinguished Expert 2017
Commented:
Hi Victor;

Thsi code snippet should give you what you need.

Dim inputXML As String = "File path and name"
Dim saveXML As String = "File path and name"
'' Load the XML document
Dim xdoc = XDocument.Load(inputXML)

Dim results As List(Of XElement) = (From n In xdoc.Descendants("ctry") _
                                    Select n).ToList()
                              
For Each node As XElement In results 
    Dim values As List(Of String) = node.Value.Split(New char() {","c}).Distinct().ToList()
    node.Value = String.Join(",", values)
Next

xdoc.Save(saveXML)

Open in new window

Author

Commented:
Thanks, I will try it and get back to you.

victor

Author

Commented:
Thank You.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial