因此,我一直在研究其中存储有文件夹结构的XML文件,并且希望能够验证文件系统中是否存在该文件夹结构。尽管有很多方法可以尝试执行此操作“ Resolve-Path”,“ Get-ChildItems”等……我希望能够构建XML结构中的路径并将其放入字符串或我可以找到的东西针对它运行测试路径。听起来很简单吧?可能对于一些经验丰富的Powershell经验丰富的人来说可能是这样,但是我对PS还是陌生的,并且在解决这个问题时有些困难。
这是带有目录结构的XML示例
<config>
<local>
<setup>
<folder name="FolderA" type="root">
<folder name="FolderC"/>
<folder name="FolderB">
<folder name="FolderD" type="thisone"/>
</folder>
</folder>
</setup>
</local>
</config>
如果子节点设置为FolderD,则最终目标是构建类似于以下内容的字符串
FolderA\FolderB\FolderD
对我来说,显而易见的是,要获得完整路径,您必须从末尾开始并向后移动节点树,然后就迷路了。目的是从可能存在的多个路径中仅选择一个路径。因此,例如,我想检查FolderD的路径。因此,我只需要构建该路径\ FolderA \ FolderB \ FolderD,然后忽略其余路径即可。
最简单的方法可能是:
name
属性值构建路径,直到type=root
命中该节点$xmlDoc = [xml] @'
<config>
<local>
<setup>
<folder name="FolderA" type="root">
<folder name="FolderC"/>
<folder name="FolderB">
<folder name="FolderD" type="thisone"/>
</folder>
</folder>
</setup>
</local>
</config>
'@
# Get the leaf element of interest.
$leafNode = $xmlDoc.SelectSingleNode('//folder[@type="thisone"]')
# Simply build up the path by walking up the node hierarchy
# until an element with attribute type="root" is found.
$path = $leafNode.name
$node = $leafNode
while ($node.type -ne 'root') {
$node = $node.ParentNode
$path = $node.name + '\' + $path #'# (ignore this - fixes syntax highglighting)
}
# Output the resulting path:
# FolderA\FolderB\FolderD
$path
基于问题原始形式的原始答案:关于使用递归从元素属性自上而下构建路径的问题仍可能会引起人们的兴趣。
通过递归,您仍然可以采用自顶向下的方法:
$xmlDoc = [xml] @'
<folder name="FolderA">
<folder name="FolderC"/>
<folder name="FolderB">
<folder name="FolderD"/>
</folder>
</folder>
'@
# Define a function that walks the specified XML element's hierarchy to
# down its leaf elements, building up a path of the values of the
# specified attribute, and outputting the path for each leaf element.
function get-LeafAttribPaths($xmlEl, $attrName, $parentPath) {
$path = if ($parentPath) { join-path $parentPath $xmlEl.$attrName } else
{ $xmlEl.$attrName }
if ($xmlEl.ChildNodes.Count) { # interior element -> recurse over children
foreach ($childXmlEl in $xmlEl.ChildNodes) {
get-LeafAttribPaths $childXmlEl $attrName $path
}
} else { # leaf element -> output the built-up path
$path
}
}
# Invoke the function with the document element of the XML document
# at hand and the name of the attribute from whose values to build the path.
$paths = get-LeafAttribPaths $xmlDoc.DocumentElement 'name'
# Output the resulting paths.
# With the above sample input:
# FolderA\FolderC
# FolderA\FolderB\FolderD
$paths
# Test paths for existence.
Test-Path $paths
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句