2013-10-17 60 views
0

我想从Entity Framework中读取EDMX文件中的实体集。XPath不能正常工作

的EDMX文件(XML格式),具有以下布局:

<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx"> 
    <edmx:Runtime> 
     <edmx:ConceptualModels> 
     <Schema Namespace="Model" Alias="Self" p1:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:p1="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm"> 
       <EntityContainer Name="EntityModel" p1:LazyLoadingEnabled="true"> 
        <EntitySet Name="TableName" EntityType="Model.TableName" /> 

我使用以下XPath获取和EntityContainer中的所有EntitySet的节点:

/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/Schema/EntityContainer/EntitySet 

但我没有得到任何结果使用此C#代码:

XmlDocument xdoc = new XmlDocument("pathtoedmx"); 
var ns = new XmlNamespaceManager(xdoc.NameTable); 
ns.AddNamespace("edmx", "http://schemas.microsoft.com/ado/2009/11/edmx"); 
ns.AddNamespace("annotation", "http://schemas.microsoft.com/ado/2009/02/edm/annotation"); 
ns.AddNamespace("p1", "http://schemas.microsoft.com/ado/2009/02/edm/annotation"); 
ns.AddNamespace("", "http://schemas.microsoft.com/ado/2009/11/edm"); 
var entitySets = xdoc.SelectNodes("/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/Schema/EntityContainer/EntitySet", ns); 

已从此工具获得XPath(http://qutoric.com/xmlquire/),因为我开始不相信自己的XPath技能,但它告诉我我已经使用了相同的XPath。

如果我删除“/模式/ EntityContainer相关/ EntitySet的”部分其寻找“/ EDMX:EDMX/EDMX:运行/ EDMX:ConceptualModels”,但不会进一步对已经尝试指定“EDMX “namespace(”edmx:/ Schema“)但没有区别。

希望你能帮助我,已经把我的头撞在桌子上。 :)

+0

是否需要,如果没有蜜蜂的XPath,您可能需要使用LinqToXml – CSharpie

回答

1

命名空间是关于如何将两种不同的XML方言合并到单个文档中的约定。只要你保持你的URI组件完全一样,那些前缀真的不重要。举例来说,采取这样的事情:

ns.AddNamespace("xxx", "http://schemas.microsoft.com/ado/2009/11/edmx"); 
Console.WriteLine(xdoc.SelectNodes("/xxx:Edmx", ns).Count); // 1 

你会得到一个节点,因为你的命名空间URI相匹配,尽管你的“错误”的命名空间前缀。

如果您有一个名为xmlns的属性,则当前元素及其子元素将继承该名称空间URI。

就你而言,你的根元素没有默认的命名空间,这没关系。但你的Schemas元素确实有一个名称空间,你需要通知它。我想出了这个代码:

// change "" to "edm" 
ns.AddNamespace("edm", "http://schemas.microsoft.com/ado/2009/11/edm"); 
var entitySets = xdoc.SelectNodes("/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/edm:Schema/edm:EntityContainer/edm:EntitySet", ns); 
+0

谢谢,你撞钉。 :) –