我正在尝试创建一个脚本来遍历InfoPath XML表单中的所有节点,我认为我的逻辑存在缺陷。在另一篇文章中,我发现xml元素中的文本被认为是text类型的另一个元素。那时我意识到我的循环逻辑必须有缺陷,因为它只找到文本元素作为最后一个元素。
在下面的代码中,我包含了简单的XML有一个没有文本的节点,然后是两个带有文本的节点。结果仅将最后一个节点显示为带有文本的单独节点。我的目标是让#text节点显示所有具有文本的元素。
function ReadAllNodes ($node) {
foreach ($childnode in $node.ChildNodes)
{
[string] $name = $childnode.Name
[string] $path = Get-XPath($childnode)
[string] $nt = $childnode.NodeType
[string] $hc = $childnode.HasChildNodes
[string] $val = $childnode.Value
[string] $txt = $childnode.'#text'
Write-Host (“Name={0}, path={1}, type={2}, hc={3}, val={4}, txt={5}” -f $name, $path, $nt, $hc,$val,$txt)
}
foreach ($cn in $childnode) {
ReadAllNodes $cn
}
}
$Xml = @"
<?xml version="1.0" encoding="utf-8"?>
<myFields>
<Folder_Section>
<NoDataNode />
<NodeWithText1>FirstText</NodeWithText1>
<NodeWithText2>SecondText</NodeWithText2>
</Folder_Section>
</myFields>
"@
$content = New-Object -TypeName XML
$content.LoadXml($Xml)
[System.Xml.XmlElement] $root = $content.get_DocumentElement()
ReadAllNodes $root
这导致:
Name=Folder_Section, path=/myFields/Folder_Section, type=Element, hc=True, val=, txt=
Name=NoDataNode, path=/myFields/Folder_Section/NoDataNode, type=Element, hc=False, val=, txt=
Name=NodeWithText1, path=/myFields/Folder_Section/NodeWithText1, type=Element, hc=True, val=, txt=FirstText
Name=NodeWithText2, path=/myFields/Folder_Section/NodeWithText2, type=Element, hc=True, val=, txt=SecondText
Name=#text, path=/myFields/Folder_Section/NodeWithText2/#text, type=Text, hc=False, val=SecondText, txt=