Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have .xml file like
XML
<?xml version="1.0" encoding="utf-8"?>
<root>
  <Folder>
    <path>C:\Users\bsushil\Documents\Sharpdesk Desktop\Tinki</path>
    <name>Tinkiiiii</name>
  </Folder>
  <Folder>
    <path>C:\Users\bsushil\Documents\Sharpdesk Desktop\Tinki\New folder</path>
    <name>New folder</name>
  </Folder>
  <Folder>
    <path>C:\Users\bsushil\Documents\Sharpdesk Desktop\Tinki\New folder (1)</path>
    <name>New folder (1)</name>
  </Folder>
</root>

I want to iterate to get the value path and name. how can I do ?

What I have tried:

I am creatin this xml using.
C#
XElement root = xmlDoc.Element("root");
          root.Add(new XElement("Folder",
              new XElement("path", item.OriginalPath),
              new XElement("name", FolderShortcutName)));
          xmlDoc.Save(folderShortcutsFilsXml);


I can iterate only path using
C#
var pathsList = xmlDoc.Descendants("path").Select(x => x.Value);

but I want path and name both and store into Dictionary<string, string>
Posted
Updated 28-Feb-18 23:11pm
v2

You could achieve your goal like this:

var xmlDocument = new XmlDocument();

xmlDocument.Load("data.xml");

var nodes = xmlDocument.DocumentElement?.SelectNodes("/root/Folder");

if (nodes == null) return;

var dictionary = nodes.Cast<XmlNode>().ToDictionary(node =>
{
	var selectSingleNode = node.SelectSingleNode("path");

	return selectSingleNode?.InnerText;
}, node =>
{
	var singleNode = node.SelectSingleNode("name");
	return singleNode?.InnerText;
});
 
Share this answer
 
Here is my working solution
C#
foreach (XElement xe in xdoc.Descendants("Folder"))
               {
                   dectionary.Add(xe.Element("name").Value, xe.Element("path").Value);
               }
 
Share this answer
 
Comments
CHill60 1-Mar-18 9:07am    
I've noticed that you have posted several solutions to your own questions and then accepted your own solution. Please be careful that your behaviour doesn't get perceived as "point farming" as it could be reported as abuse of the site. If someone else's solution has helped you make sure that you credit them properly - you can accept more than one solution if necessary. For example: How to pass the json string to client.postasync() method in C#?[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900