1
$club = $xml.CreateElement('xi:include')
$club.SetAttribute('href','barracas')
$lookupNode.AppendChild($club) >$null
$xml.Save($config_filename)

In the above PowerShell fragment $lookupNode is the node where I am appending a newly created node $club.

What I expect is to add the line below.

<xi:include href="barracas" />

What actually I get is a line below.

<include href="barracas" xmlns="" />

The problems are:

  1. I need xi:include but it starts with include.
  2. I am getting xmlns="", which I don't need.
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Muhammad VP
  • 107
  • 2
  • 6

1 Answers1

3

A colon-separated prefix in XML elements indicates a namespace.

<foo:bar baz='something'>else</foo:bar>
  ^   ^   ^       ^       ^
  |   |   |       |       `- node value/text
  |   |   |       `- attribute value/text
  |   |   `- attribute name
  |   `- node name
  `- namespace name

You need a namespace manager for handling these:

[Xml.XmlNamespaceManager]$nsm = $xml.NameTable
$nsm.AddNamespace('ns', $xml.DocumentElement.NamespaceURI)
$nsm.AddNamespace('xi', 'http://...')

$club = $xml.CreateElement('xi:include', $ns.LookupNamespace('xi'))
$club.SetAttribute('href', 'barracas')
$xml.DocumentElement.AppendChild($club) >$null

Also see this related question.

Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • I am getting like this : How can I remove xmlns:xi=" xmlns xml" and make a line like – Muhammad VP Feb 27 '16 at 09:28
  • @MuhammadVP To avoid that you need to explicitly add and look up the `xi` namespace. See updated answer. – Ansgar Wiechers Feb 27 '16 at 12:00
  • @MuhammadVP What are you talking about? For an `` element to work there should already be a definition `xmlns:xi="http://..."` elsewhere in the XML. You can't use namespaced elements without the namespace being defined. `AddNamespace()` just informs the namespace manager about the namespace. – Ansgar Wiechers Feb 28 '16 at 13:19
  • Is this a namespace/node with a `namespaced attr`? ` – Timo Jun 22 '21 at 18:28