问题
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