使用命名空间解析xml(edmx)属性

时间:2013-06-10 15:00:06

标签: c# .net xpath xml-parsing edmx

我正在尝试从edmx xml解析m:MaxDataServiceVersion的值,其开头如下:

<edmx:Edmx Version="1.0">
<edmx:DataServices m:DataServiceVersion="1.0" m:MaxDataServiceVersion="3.0">
<Schema Namespace="NorthwindModel">
<EntityType Name="Category">

以下代码返回所需元素

string nav = navigator.SelectSingleNode("//*[local-name() = 'DataServices']");

但我尝试获取属性值的所有尝试都没有成功。这是我尝试过的:

string nav = navigator.SelectSingleNode("//*[local-name() = 'DataServices']").GetAttribute("@{m}MaxDataServiceVersion", "");
nav = navigator.SelectSingleNode("//*[local-name() = 'DataServices']").GetAttribute("m:MaxDataServiceVersion", "");
nav = navigator.SelectSingleNode("//*[local-name() = 'DataServices']").GetAttribute("MaxDataServiceVersion", "");
nav = navigator.SelectSingleNode("//*[local-name() = 'DataServices']").GetAttribute("MaxDataServiceVersion", "m");
nav = navigator.SelectSingleNode("//*[local-name() = 'DataServices']").GetAttribute("MaxDataServiceVersion", "edmx:m");

运行以下代码

XPathNodeIterator nodes = navigator.Select("//*[local-name() = 'DataServices']");
while (nodes.MoveNext())
{
    XPathNavigator navigator2 = nodes.Current.Clone();
    navigator2.MoveToFirstAttribute();
    Console.WriteLine("{0} = {1}", navigator2.Name, navigator2.Value);

    while (navigator2.MoveToNextAttribute())
    {
        Console.WriteLine("{0} = {1}", navigator2.Name, navigator2.Value);
    }

    Console.WriteLine();
}

将输出两个属性

m:DataServiceVersion = 1.0
m:MaxDataServiceVersion = 3.0

但是应该可以获得所需的一个而不需要遍历所有这些,我想......

那么有没有办法获得m:MaxDataServiceVersion值而不循环?

1 个答案:

答案 0 :(得分:1)

XML以

开头
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"><edmx:DataServices m:DataServiceVersion="1.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">

所以访问每个DataServices元素的属性的一种方法是

XmlNamespaceManager nsMgr = new XmlNamespaceManager(navigator.NameTable);
nsMgr.Add("edmx", "http://schemas.microsoft.com/ado/2007/06/edmx");

foreach (XPathNavigator dataServices in navigator.Select("edmx:DataServices", nsMgr))
{
  string version = dataServices.GetAttribute("MaxDataServiceVersion", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
}

如果你想要第一个这样的属性的属性值,那么

nsMgr.Add("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
string version = navigator.SelectSingleNode("//edmx:DataServices/@m:MaxDataServiceVersion", nsMgr).Value;

应该足够了。