Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

c# - Using the XElement.Elements method, can I find elements with wildcard namespace but the same name?

Trying to do a simple parse of an XML document. What's the easiest way to pull out the two PropertyGroups below?

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
     1
  </PropertyGroup>
  <PropertyGroup xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
     2
  </PropertyGroup>
</Project>

I have been trying to use XElement.Elements(XName) but to do so I need to prefix PropertyGroup with the xmlns. The issue is that I don't care about the name space and if it changes in future I would still like all PropertyGroups to be retrieved.

 var xml = XElement.Load(fileNameWithPath);
 var nameSpace = xml.GetDefaultNamespace();

 var propertyGroups= xml.Elements(nameSpace + "PropertyGroup");

Can you improve on this code such that I don't need to prepend with nameSpace? I know I can essentially just reimplement the Elements method but I was hoping there was some way to pass a wildcard namespace?

Thanks,

Gavin

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Does this work for you?

xml.Elements().Where(e => e.Name.LocalName == "PropertyGroup")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...