What is the syntax for accessing child nodes using System.Xml.XmlDocument.SelectNodes with a namespace?

一曲冷凌霜 提交于 2020-01-17 04:16:42

问题


Given the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2014-12-03T13:58:05.5136628</Date>
    <Author>ABCCORP\jsmith</Author>
  </RegistrationInfo>
</Task>

I can access the Task node using SelectNodes as follows:

[xml]$xml = gc C:\temp\myxml.xml
$ns = new-object Xml.XmlNamespaceManager $xml.NameTable
$ns.AddNamespace("ns0", "http://schemas.microsoft.com/windows/2004/02/mit/task")
$xml.SelectNodes("ns0:Task", $ns)

But I can't access child nodes. For example, this returns null:

$xml.SelectNodes("ns0:Task/RegistrationInfo", $ns)

What is the correct syntax for accessing child nodes?


回答1:


You have unprefixed namespace declaration, which also known as default namespace, here :

<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">

Note that not only element where default namespace declared is in that namespace, but all descendant elements inherit ancestor default namespace implicitly, unless otherwise specified (using explicit namespace prefix or local default namespace that point to different namespace uri). That means, in this case, all elements including RegistrationInfo are in default namespace, and that's why @PetSerAl suggested to use ns0 prefix for RegistrationInfo as well :

$xml.SelectNodes("ns0:Task/ns0:RegistrationInfo", $ns)


来源:https://stackoverflow.com/questions/31127264/what-is-the-syntax-for-accessing-child-nodes-using-system-xml-xmldocument-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!