使用 LINQ 从 XML 中提取属性
我有以下 XML 文件(实际上是 VS2010 dbproj 文件),
<?xml version="1.0" enconding="utf-8"?>
<Project.....>
<propertyGroup>
....
</PropertyGroup>
<ItemGroup>
<Build Include = "Schema Objects\Schemas\dbo\Programmability\Stored Procedures\foo.sql>
</Build>
</ItemGroup>
</Project>
我想使用 LINQ to XML 提取作为存储过程的所有构建元素。 我有以下代码,但似乎不起作用:
var doc = XDocument.Load(filePath);
var elements = doc.Descendants("Build").Where( x => x.Attribute("Include").Value.Contains("Stored Procedure")).ToList();
What is the right way of extract the attribute value?
感谢您的回复!结果发现,Project 标签中指定了一个命名空间,但我省略了。这就是为什么我得到 0 结果的原因。
I have the following XML file (it's actually VS2010 dbproj file)
<?xml version="1.0" enconding="utf-8"?>
<Project.....>
<propertyGroup>
....
</PropertyGroup>
<ItemGroup>
<Build Include = "Schema Objects\Schemas\dbo\Programmability\Stored Procedures\foo.sql>
</Build>
</ItemGroup>
</Project>
I would like to use LINQ to XML to extract all Build elements that are Stored Procedures.
I have the following code, which doesn't seem to work:
var doc = XDocument.Load(filePath);
var elements = doc.Descendants("Build").Where( x => x.Attribute("Include").Value.Contains("Stored Procedure")).ToList();
What is the right way of extracting the attribute values?
Thanks for the replies! It turned out that there was a namespace specified in the Project tag which I omitted. That's why I was getting 0 results back.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PS这种方法不需要检查每个变量是否为空,例如:
P.S. this approach doesn't require check against null every variable, e.g.:
一旦修复了 XML(缺少结束引号,并且那里有不匹配的标签),它就可以正常工作。在 LINQPad 中测试
结果是:
如果您只是想获取该值,请尝试以下操作:
编辑 - 这也有效:
Once you fix the XML (you're missing a closing quote, and you have unmatched tags there), it works fine. Tested in LINQPad
Result is:
If you are just trying to get the value, try this:
EDIT - This works too: