3
votes

I have an xml file "1.xml":

<configuration >
  <application>
    <name>My Application</name>
  </application>
  <log level="info" />
</configuration>

and want to change text in name node from "My Application" to "Name from Powershell". I can do it like this:

$xml = [xml](Get-Content "1.xml");
$nameNode = $xml.configuration.application.ChildNodes.Item(0);
$nameNode.InnerText = "Name from Powershell";

But I don't like the idea to get the node by index. I want to get it by name. But this variants don't work for me:

$nameNode = $xml.configuration.application.name;

$nameNode = $xml.SelectSingleNode("//configuration/application/name");

Is there a simple way to get an element by name in PowerShell?

1
$xml.configuration.application.name definitely works, and setting this to a new value changes the element contents. If it "doesn't work for you", you'll have to be more specific as to what it is that's not working. - Jeroen Mostert

1 Answers

4
votes

Following works for me. As @Jeroen said, you'll have to be more specific and provide a runnable script that shows what doesn't work.

$xml = [xml]@"
<configuration >
  <application>
    <name>My Application</name>
  </application>
  <log level="info" />
</configuration>
"@

$xml.configuration.application.name # Outputs "My Application"
$xml.configuration.application.name = "Test"
$xml.configuration.application.name # Outputs "Test"