英文:
Can't change value of nodes with same name
问题
以下是您的XML文件示例:
<?xml version="1.0" encoding="ISO-8859-1"?>
<sc>
<fluxs>
<flux>
<cible>
<id>0</id>
</cible>
</flux>
<flux>
<cible>
<id>1</id>
</cible>
</flux>
<flux>
<cible>
<id>2</id>
<wsdl_url>a</wsdl_url>
<wsdl_url>b</wsdl_url>
</cible>
</flux>
</fluxs>
</sc>
我想要更改“wsdl_url”节点的值。
我尝试了这样做:
$xml = [xml](get-content "c:\mme.xml")
# 这个有效
write-host "Before" $xml.sc.fluxs.flux[2].cible.id
$xml.sc.fluxs.flux[2].cible.id = "Other"
write-host "After" $xml.sc.fluxs.flux[2].cible.id
# 这个不起作用
write-host "Before" $xml.sc.fluxs.flux[2].cible.wsdl_url[0]
$xml.sc.fluxs.flux[2].cible.wsdl_url[0] = "AA"
write-host "After" $xml.sc.fluxs.flux[2].cible.wsdl_url[0]
在第一部分中,在更改id节点的值后,我得到了新值("Other")。
在第二部分中,没有任何更改。出了什么问题?
英文:
Here is my XML file example :
<?xml version="1.0" encoding="ISO-8859-1"?>
<sc>
<fluxs>
<flux>
<cible>
<id>0</id>
</cible>
</flux>
<flux>
<cible>
<id>1</id>
</cible>
</flux>
<flux>
<cible>
<id>2</id>
<wsdl_url>a</wsdl_url>
<wsdl_url>b</wsdl_url>
</cible>
</flux>
</fluxs>
</sc>
I want to change the value of nodes "wsdl_url"
I tried this :
$xml = [xml](get-content "c:\mme.xml")
# This works
write-host "Before" $xml.sc.fluxs.flux[2].cible.id
$xml.sc.fluxs.flux[2].cible.id = "Other"
write-host "After" $xml.sc.fluxs.flux[2].cible.id
# This does not work
write-host "Before" $xml.sc.fluxs.flux[2].cible.wsdl_url[0]
$xml.sc.fluxs.flux[2].cible.wsdl_url[0] = "AA"
write-host "After" $xml.sc.fluxs.flux[2].cible.wsdl_url[0]
In the first part, after having change que value of the id node, I get the new value ("Other").
In the second part, nothing change. Whats's wrong ?
答案1
得分: 1
根据评论中所述,您可以使用SelectNodes
方法来获取所有wsdl_url
节点,然后由您决定要为每个节点使用哪些值。例如,以下代码通过索引更新现有节点:
$nodes = $xml.SelectNodes('//cible/wsdl_url')
$nodes[0].'#text' = 'hello'
$nodes[1].'#text' = 'world'
$xml.Save('path\to\new.xml')
然后更新后的XML将如下所示:
<?xml version="1.0" encoding="ISO-8859-1"?>
<sc>
<fluxs>
<flux>
<cible>
<id>0</id>
</cible>
</flux>
<flux>
<cible>
<id>1</id>
</cible>
</flux>
<flux>
<cible>
<id>2</id>
<wsdl_url>hello</wsdl_url>
<wsdl_url>world</wsdl_url>
</cible>
</flux>
</fluxs>
</sc>
英文:
As stated in comments, you can use SelectNodes
method to get all wsdl_url
nodes and from there is up to you what values would you like to use for each one of them. i.e. the below updates both existing nodes by index:
$nodes = $xml.SelectNodes('//cible/wsdl_url')
$nodes[0].'#text' = 'hello'
$nodes[1].'#text' = 'world'
$xml.Save('path\to\new.xml')
Then the updated XML would look like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<sc>
<fluxs>
<flux>
<cible>
<id>0</id>
</cible>
</flux>
<flux>
<cible>
<id>1</id>
</cible>
</flux>
<flux>
<cible>
<id>2</id>
<wsdl_url>hello</wsdl_url>
<wsdl_url>world</wsdl_url>
</cible>
</flux>
</fluxs>
</sc>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论