C#针对XmlDocument

时间:2017-07-26 13:53:34

标签: c# xml xpath xml-parsing

我正在编写一个C#程序,我希望将一系列XPath语句存储为字符串,并根据XMLDocument(或其他一些C#XML结构,如果有更好的用于此目的)对它们进行评估并存储在字典/对象中产生的值。

我的挑战是我的XPath无法被评估。

作为一个非常简单的例子,假设这是我的XML:

<root>
    <a>
        <child1 Id="Id1" Name="Name1" />
        <child2 Id="Id2" Name="Name2" />
    </a>
</root>

,例如,我的一个XPath是:

//a/*[@Id='Id1']/name()

(使用a属性=&#34; Id1&#34;获取Id的子元素的名称。

我试图写的代码的简化版本是:

var xpath = @"//a/*[@Id='Id1']/name()";
var xml = @"<root><a><child1 Id='Id1' Name='Name1' /><child2 Id='Id2' Name='Name2' /></a></root>";

var doc = new XmlDocument();
doc.LoadXml(xml);
var navigator = doc.CreateNavigator();

string ChildName = (string)navigator.Evaluate(xpath);

但是我收到的错误是我的XPath有一个无效的令牌 - 我假设它是name()部分。

有没有办法使用直接XPath语句而不是遍历树来实现这一点?

谢谢!

2 个答案:

答案 0 :(得分:4)

如果我理解正确的话,你肯定需要重新安排你的XPath。试试这个:

name(//a/*[@Id='Id1'])

答案 1 :(得分:0)

使用xml liinq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication68
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = "<root>" +
                            "<a>" +
                                "<child1 Id=\"Id1\" Name=\"Name1\" />" +
                                "<child2 Id=\"Id2\" Name=\"Name2\" />" +
                            "</a>" +
                        "</root>";

            XDocument doc = XDocument.Parse(xml);

            Dictionary<string, string> dict = doc.Descendants("a").FirstOrDefault().Elements().Where(x => x.Name.LocalName.StartsWith("child"))
                .GroupBy(x => (string)x.Attribute("Id"), y => (string)y.Attribute("Name"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }


}
相关问题