AnhNguyen
AnhNguyen

Reputation: 67

Can't get value of xml node

I have an XML file :

 <?xml version="1.0" encoding="utf-8"?>
<Projects>
<Project>
    <Name>CELL</Name>
    <FunctionList>
        <Function>guildline_addproperties</Function>
        <Function>guildline_emptylaunchcondition</Function>
        <Function>msi_setvolumelabel</Function>
    </FunctionList>
</Project>
<Project>
    <Name>AXA</Name>
    <FunctionList>
        <Function>guildline_addproperties</Function>
        <Function>guildline_emptylaunchcondition</Function>
        <Function>msi_setvolumelabel</Function>
    </FunctionList>
</Project>  
</Projects>

My code is:

string fileFolderpath = Path.GetDirectoryName(Application.ExecutablePath) + "\\Config";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(fileFolderpath + @"\FunctionTemplate.xml");
XmlNodeList xNode = xDoc.SelectNodes(String.Format("/Projects/Project [Name='{0}']/FunctionList/Function", "CELL"));

My node list has no item after running it. Is there anything wrong with my code?

Any help would be great.

Upvotes: 2

Views: 90

Answers (2)

DaniCE
DaniCE

Reputation: 2421

The following is working to me:

var xml = @"<Projects>
<Project>
    <Name>CELL</Name>
    <FunctionList>
        <Function>guildline_addproperties</Function>
        <Function>guildline_emptylaunchcondition</Function>
        <Function>msi_setvolumelabel</Function>
    </FunctionList>
</Project>
<Project>
    <Name>AXA</Name>
    <FunctionList>
        <Function>guildline_addproperties</Function>
        <Function>guildline_emptylaunchcondition</Function>
        <Function>msi_setvolumelabel</Function>
    </FunctionList>
</Project>  
</Projects>";

             XmlDocument xDoc = new XmlDocument();
             xDoc.LoadXml(xml);
             XmlNodeList xNode = xDoc.SelectNodes(String.Format(@"/Projects/Project[Name='{0}']/FunctionList/Function", "CELL"));
             Assert.AreEqual(3, xNode.Count);

are you sure you are loading the file correctly?

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101691

I would use LINQ to XML for this:

var xmlDocument = XDocument.Load("path");

var project = xmlDocument.Root
             .Elements("Project")
             .FirstOrDefault(p => (string)p.Element("Name") == "CELL");

if(project != null)
{
   var functions = project.Descendants("Function");
}

Upvotes: 2

Related Questions