【发布时间】:2014-12-19 11:35:39
【问题描述】:
我正在尝试使用以下方法从 XDocument 中提取元素:
private bool ContainsEntity(FileInfo filePath, string entityType, int id, string field, string value)
{
try{
var doc = XDocument.Load(filePath.FullName);
var entities = doc.Descendants(entityType);
var ns = XNamespace.Get("http://schemas.sage.com/sdata/2008/1");
var attr = new XAttribute(ns + "uuid", id);
var specificEntities = entities.Where(y =>
{
var atts = y.Attributes();
return atts.Contains(attr);
});
return specificEntities.Any(ent =>
ent.Elements(field).Any(f => f.Value.Equals(value, StringComparison.OrdinalIgnoreCase)));
}catch{return false;}
}
xml 文档中的相关元素如下所示:
<?xml version=""1.0"" encoding=""utf-8""?>
<feed xmlns=""http://www.w3.org/2005/Atom"" xmlns:sdata=""http://schemas.sage.com/sdata/2008/1"" xmlns:http=""http://schemas.sage.com/sdata/http/2008/1"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:mybi=""http://schemas.sage.com/mybi/import/2011"" xmlns:cs=""urn:cs"">
<author>
<name>Sage UK</name>
</author>
<category />
<generator version=""Sage Business Sync 1.0.0.0, Resources Package 0.1.0"" />
<id />
<title>Sage 200 UK Synchronization feed</title>
<mybi:contractVersion>1.2.5</mybi:contractVersion>
<mybi:resourceKind>depotStore</mybi:resourceKind>
<entry xmlns="""">
<author>
<name>Sage UK</name>
</author>
<id>1</id>
<title>operatingCompanyResource</title>
<updated>2014-12-19T10:32:43.501+00:00</updated>
<sdata:payload>
<depotStore sdata:uuid=""1"">
<operatingCompanyReference>1</operatingCompanyReference>
<originalType>
operatingCompanyWarehouse
</originalType>
<type>
operatingCompanyWarehouse
</type>
<name>warehouse1</name>
</depotStore>
</sdata:payload>
</entry>
</feed>";
问题是属性不匹配,所以 specificEntities 总是一个零长度的集合。问题似乎与属性名称的命名空间前缀有关,但我看不到如何将 attr 初始化为所需的值。
【问题讨论】:
-
你能发布一个包含
sdata定义的XML块吗?不仅仅是元素。 -
@RahulSingh 我用完整的 xml 文档的示例编辑了问题
标签: c# xml linq linq-to-xml