deserialize a list of Guid c#

1k Views Asked by At

Can anyone help me to deserialize this xml file into a list of Guid ?

<?xml version="1.0" encoding="UTF-8"?>
<content>
    <0>124179e5-82b9-c551-1e88-515ec3bbe4e3</0>
    <1>5c8246d3-5b9f-16bb-89dc-515ec4674170</1>
    <2>9d7f4701-81e3-3c90-c743-515ec9580852</2>
    <3>ea8d97bd-243b-b917-bc15-51764c2b2f34</3>
</content>

Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

Your file isn't a valid XML file. According to the W3C website, node identifiers cannot start with digits. Not respecting the actual node identifiers, he common way to read your list would be:

List<Guid> guids = new List<Guid>();
XmlDocument doc = new XmlDocument();
doc.Load(@"guids.xml");
foreach(XmlNode guidNode in doc["content"].ChildNodes) {
    guids.Add(Guid.Parse(guidNode.Name));
}
1
On

Using xml here is making things more complex than it needs to be. I suggest refactoring your file as follows:

guids.txt:

124179e5-82b9-c551-1e88-515ec3bbe4e3
5c8246d3-5b9f-16bb-89dc-515ec4674170
9d7f4701-81e3-3c90-c743-515ec9580852
ea8d97bd-243b-b917-bc15-51764c2b2f34

Code (C#):

List<Guid> guids = File.ReadAllLines(@"guids.txt").Select(l => Guid.Parse(l)).ToList();