具有命名空间的 XPath 选择节点 [英] XPath select node with namespace

查看:42
本文介绍了具有命名空间的 XPath 选择节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是一个 .vbproj,看起来像这样

Its a .vbproj and looks like this

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <ProjectGuid>15a7ee82-9020-4fda-a7fb-85a61664692d</ProjectGuid>

我想要的只是 ProjectGuid,但是当存在命名空间时它不起作用...

all i want to get is the ProjectGuid but it does not work when a namespace is there...

 Dim xmlDoc As New XmlDocument()
 Dim filePath As String = Path.Combine(mDirectory, name + "\" + name + ".vbproj")
 xmlDoc.Load(filePath)
 Dim value As Object = xmlDoc.SelectNodes("/Project/PropertyGroup/ProjectGuid")

我该怎么做才能解决这个问题?

what can i do to fix this?

推荐答案

执行此类操作的最佳方法 (恕我直言) 是创建命名空间管理器.这可用于调用 SelectNodes 来指示哪些命名空间 URL 连接到哪些前缀.我通常会设置一个静态属性,它会返回一个这样的足够实例(它是 C#,你必须翻译):

The best way to do things like this (IMHO) is to create a namespace manager. This can be used calling SelectNodes to indicate which namespace URLs are connected to which prefixes. I normally set up a static property that returns an adequate instance like this (it's C#, you'll have to translate):

private static XmlNamespaceManager _nsMgr;
public static XmlNamespaceManager NsMgr
{
  get
  {
    if (_nsMgr == null)
    {
      _nsMgr = new XmlNamespaceManager(new NameTable());
      _nsMgr.AddNamespace("msb", "http://schemas.microsoft.com/developer/msbuild/2003");
    }
    return _nsMgr;
  }
}

我在这里只包含一个命名空间,但您可以有多个.然后你可以像这样从文档中选择:

I include only one namespace here, but you could have multiple. Then you can select from the document like this:

Dim value As Object = xmlDoc.SelectNodes("/msb:Project/msb:PropertyGroup/msb:ProjectGuid", NsMgr)

请注意,所有元素都在指定的命名空间中.

Note that all of the elements are in the specified namespace.

这篇关于具有命名空间的 XPath 选择节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆