无法获取xml节点的值

时间:2014-07-22 11:02:19

标签: c# xml

我有一个XML文件:

 <?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>

我的代码是:

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"));

我的节点列表在运行后没有项目。我的代码有什么问题吗?

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:2)

我会使用LINQ to XML

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");
}

答案 1 :(得分:0)

以下内容对我有用:

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);

您确定要正确加载文件吗?