Powershell和XML子节点

时间:2014-04-07 13:30:29

标签: xml powershell

我有这个XML:

<?xml version="1.0" encoding="utf-8"?>
<Man schemaVersion="1">
    <version>2.2</version>
    <file>
        <properties>
        …
        </properties>
        <group> 
            <properties>
        ...
            </properties>
        </group>                     
        <group>
            <properties>
        …
            </properties>       
            <group>
                <properties>
                    <items>
                        <name>test</name>
                        <description>A test</description>
                    </items>
                </properties>
            </group>
            <group>
                <properties>
                    <items>
                        <name>test2</name>
                        <description>A test field again</description>
                    </items>
                </properties>
            </group>
        </group>
    </file>
</Man>

我想用powershell添加一个子节点(?)包含以下内容:

    <group>
        <properties>
            <items>
                <name>test3</name>
                <description>one more field</description>
            </items>
        </properties>
    </group>

正好位于test2节点下面,如下所示:

    <group>
        <properties>
            <items>
                <name>test</name>
                <description>A test</description>
            </items>
        </properties>
    </group>
    <group>
        <properties>
            <items>
                <name>test2</name>
                <description>A test field again</description>
            </items>
        </properties>
    </group>
    <group>
        <properties>
            <items>
                <name>test3</name>
                <description>one more field</description>
            </items>
        </properties>
    </group>

问题在于&#34;组&#34;被识别为数组,我无法向数组添加元素。我尝试了很多技巧来添加元素但不在数组中

代码(正如我所说,它处于初级阶段,我首先关注的是获得一些测试值。

$strXMLfile="c:\blabla\bla.xml";
$xml=get-content $strXMLfile;
$xmlRoot=$xml.get_DocumentElement();
$xmlnode=$xmlRoot.file.group;
$group=0;
while (!($xmlnode[$group].properties.name -eq "test node")) {
    $group++
}
$nodesGroups=$xmlnode[$group].group;
if ($nodesGroups.count -eq $null) {
    $intNewGroup=2
}   
else {
    $intNewGroup=$nodesGroups.count+1
}

#Here should be the code for the group,properties,items line creation. Partially

$newline=$xml.CreateElement("items")

#Here should be the code for the <name>. Not ready yet

2 个答案:

答案 0 :(得分:0)

您可以使用XmlElement方法将新的最后一个子项添加到现有元素(类型AppendChild)。因此,不是操纵<group>元素的数组,而是操纵它们的共同父元素(<file>元素)。

答案 1 :(得分:0)

希望这可以让你开始:

 > $xml = [XML]"<Man>...</Man>"
 > $newGrp = $xml.CreateElement("group")
 > $newGrp.InnerText = "group 3"
 > $xml.Man.file.group.AppendChild($newGrp)