更改 .NET 中的默认 XML xmlns 命名空间值
我需要从 VS 项目文件中获取文件列表。 csproj文件是XML文件,所以我使用linq to xml来解析它。问题出在 csproj 文件的默认命名空间中,其声明如下:
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
这是我用来在 csproj 文件中查找“编译”元素的代码:
XmlReader reader = XmlReader.Create(projectFilePath);
XDocument doc = XDocument.Load(reader);
XmlNameTable nameTable = reader.NameTable;
XmlNamespaceManager nsManager = new XmlNamespaceManager(nameTable);
XNamespace nms = doc.Root.GetDefaultNamespace();
nsManager.AddNamespace("", nms.NamespaceName);
List<XElement> csFiles = new List<XElement>(doc.Root.XPathSelectElements("//Compile", nsManager));
doc.Root.XPathSelectElements
返回一个空列表。
nsManager.DefaultNamespace
的值为“http://schemas.microsoft.com/developer/msbuild/2003”。 但是 nsManager.LookupNamespace("xmlns") 会返回默认的 XML 命名空间:“http://www.w3.org/2000/xmlns/”。
如何更改 xmlns 命名空间值?
I need to get a list of files from a VS project file. csproj file is XML file, so I use linq to xml to parse it. The problem is in default namespace of csproj file, it is declared like:
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
Here is the code I use to find "Compile" elements in a csproj file:
XmlReader reader = XmlReader.Create(projectFilePath);
XDocument doc = XDocument.Load(reader);
XmlNameTable nameTable = reader.NameTable;
XmlNamespaceManager nsManager = new XmlNamespaceManager(nameTable);
XNamespace nms = doc.Root.GetDefaultNamespace();
nsManager.AddNamespace("", nms.NamespaceName);
List<XElement> csFiles = new List<XElement>(doc.Root.XPathSelectElements("//Compile", nsManager));
doc.Root.XPathSelectElements
returns an empty list.
nsManager.DefaultNamespace
has value "http://schemas.microsoft.com/developer/msbuild/2003".
But nsManager.LookupNamespace("xmlns")
returns default XML namespace: "http://www.w3.org/2000/xmlns/".
How to change the xmlns namespace value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是您需要使用 XPath 明确命名空间。它不仅仅使用文档的默认值,您还必须为其命名。
如果将最后两行更改为类似这样的内容,它将起作用(我选择了 xmlns 前缀“default”):
另一种选择是使用 XContainer 方法。这样你就不需要担心使用命名空间管理器:
Your problem is that you need to be explicit about the namespace with the XPath. It won't just use the default one for the document, you have to name it.
If you change the last two lines to something like this, it will work (I chose the xmlns prefix "default"):
Another option is to use the XContainer methods instead. This way you don't need to worry about using a namespace manager: