我有两个XML文件,如下所示。
XML文件1:
<tag1>
<pmtinf>
<srn>1111</srn>
</pmtinf>
<pmtinf>
<srn>2222</srn>
</pmtinf>
<pmtinf>
<srn>3333</srn>
</pmtinf>
</tag1>
XML文件2:
<tag2>
<inf>
<srn>1111</srn>
<sometag>abcdf</sometag>
</inf>
<inf>
<srn>4444</srn>
<sometag>zxcz</sometag>
</inf>
<inf>
<srn>5555</srn>
<sometag>vcxv</sometag>
</inf>
</tag2>
从第二个文件中我得到srn标记值,然后我需要在第一个文件中找到匹配的srn(只有一个匹配)并在匹配的srn的pmtinf标记中添加newtag(我需要获取sometag的值并添加到newtag )并保存新的XML。结果应该是这样的。
<tag1>
<pmtinf>
<srn>1111</srn>
<newtag> abcdf</newtag>
</pmtinf>
<pmtinf>
<srn>2222</srn>
</pmtinf>
<pmtinf>
<srn>3333</srn>
</pmtinf>
</tag1>
我的代码:
# get all srns
[xml]$XML1 = Get-Content -Path "\\XML1.xml"
# loop through XML1 file's srns
foreach ($srn1 in $XML1.tag1.pmtinf.srn) {
# loop through XML2 files
[xml]$XML2 = Get-Content -Path "\\XML2.xml"
# check and find file where current SRN exists
foreach ($srn2 in $XML2.tag2.inf|where{$_.srn -eq $srn1}) {
$sometag = $srn2.tag2.inf.sometag
# Here I need to add sometag as a new tag in XML file 1 and save it. But
# I Don't know how to find exact needed pmtinf node and add <newtag>
# there.
}
}