If I have the following xml:
<staff>
<employee>
<Name>Bob Smith</Name>
<function>management</function>
<age>39</age>
<stuff>
<data>Some Data</data>
</stuff>
</employee>
<employee>
<Name>Sam Jones</Name>
<function>security</function>
<age>24</age>
<stuff>
<data>Some Other Data</data>
</stuff>
</employee>
</staff>
I can access this with:
$FilePath = "c:\test.xml"
$XmlFiles = @()
$Index = -1
$xdoc = new-object System.Xml.XmlDocument
$xdoc.load($FilePath)
$xdoc.SelectNodes("//employee")
This returns all the information.
But for < stuff >
it just says stuff
, it doesn't expand it to show the content of the < data >
field.
How can I get it to show everything for each employee, including the < data >
field?
答案 0 :(得分:0)
遍历节点已在c#中多次回答。这只是对Powershell的翻译。 Following an Example in C#
$FilePath = "c:\test.xml"
$XmlFiles = @()
$Index = -1
$xdoc = new-object System.Xml.XmlDocument
$xdoc.load($FilePath)
$xdoc.SelectSingleNode("staff")
function TraverseNodes(
[System.Xml.XmlLinkedNode] $root #XmlNode
)
{
if ($root -is [System.Xml.XmlElement])
{
Write-Host($root.Name)
if ($root.HasChildNodes)
{
TraverseNodes($root.FirstChild)
}
if ($root.NextSibling -ne $null)
{
TraverseNodes($root.NextSibling)
}
}
elseif ($root -is [System.Xml.XmlText])
{
$text = $root.InnerText
Write-Host $text
}
elseif ($root -is [System.Xml.XmlComment])
{
$text = $root.InnerText
Write-Host $text
if ($root.HasChildNodes)
{
TraverseNodes($root.FirstChild)
}
if ($root.NextSibling -ne $null)
{
TraverseNodes($root.NextSibling)
}
}
}
$xdoc.ChildNodes |%{TraverseNodes $_ }
的原始解决方案