如何从带有节点的函数返回 XML 文件? [英] How to return an XML file from a function with a node?
问题描述
我有一个简单的 XML
I have a simple XML
<bds>
<bd>
<id>10</id>
<user>john</user>
<servers>
<name>pc24</name>
</servers>
</bd>
<bd>
<id>12</id>
<user>peter</user>
<servers>
<name>pc25</name>
</servers>
</bd>
我有一个函数,我希望它返回一个 XML 文件,其中包含挂在节点上的所有元素.
I have a function and I would like it to return an XML file with all the elements that hang from a node.
$collection = "bds"
$attribute = "name"
$obj = "pc25"
function test () {
if ($xml.SelectNodes("//$attribute").name -eq "name") {
return $xml.SelectNodes("//$attribute").parentnode | Where $attribute -eq $obj
}
else {
return $false
}
}
我希望函数的输出是:
<id>12</id>
<user>peter</user>
<servers>
<name>pc25</name>
</servers>
如何生成带有函数返回的 XML 文件?
How can I generate an XML file with the return of the function?
推荐答案
您可以使用稍微智能的 XPath 来选择您的节点,然后使用 InnerXml
属性来获取您想要的输出字符串:
You can use a slightly smarter XPath to select your nodes, and then the InnerXml
property to get the output string you're after:
PS> $xml = [xml] @"
<bds>
<bd>
<id>10</id>
<user>john</user>
<servers>
<name>pc24</name>
</servers>
</bd>
<bd>
<id>12</id>
<user>peter</user>
<servers>
<name>pc25</name>
</servers>
</bd>
</bds>
"@
PS> $xml.SelectNodes("bds/bd[servers/name = 'pc25']").InnerXml
<id>12</id><user>peter</user><servers><name>pc25</name></servers>
注意 - bds/bd[servers/name = 'pc25']
表示找到所有具有子 servers/的
节点,值为bds/bd
节点名称pc25
".
Note - bds/bd[servers/name = 'pc25']
means "find all the bds/bd
nodes that have a child servers/name
node with a value pc25
".
然后,您可以根据需要使用 XPath 字符串中的变量值将其改装回您的函数...
You can then retro-fit this back into your function using your variable values in the XPath string as appropriate...
这篇关于如何从带有节点的函数返回 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!