3

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
  • 3
    $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. Commented Apr 25, 2017 at 14:41

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Lieven and @Jeroen, you were right, $xml.configuration.application.name works. My mistake was: I thought it returns an object with properties and tried to do things like this: $xml.configuration.application.name.InnerText = "Test"
been there <g>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.