简体   繁体   English

使用名称空间添加XML属性

[英]Add XML Attribute with namespace

I'm trying to add elements to an automatically generated XML file that I can then import back into the generator, but I'm running into an issue with some namespace attributes. 我正在尝试将元素添加到自动生成的XML文件中,然后可以将其重新导入到生成器中,但是遇到一些名称空间属性的问题。

Here is what I'm trying to recreate: 这是我要重新创建的内容:

<IP_Filter_Template_Guid dt:dt="string" xmlns:dt="urn:schemas-microsoft-com:datatypes">

Here is the code I'm using: 这是我正在使用的代码:

$xml = [System.Xml.XmlDocument](Get-Content $xmldoc)

$child1element = $xml.CreateElement($rapname)
$child1element.SetAttribute("name", $rapname)
$child1 = $xml.Root.Children.Microsoft_Internet_Authentication_Service.Children.RadiusProfiles.Children.AppendChild($child1element)

$child2element = $xml.CreateElement("Properties")
$child2 = $child1.AppendChild($child2element)

$child3element1 = $xml.CreateElement("IP_Filter_Template_Guid", $xmlns)
$child3element1.SetAttribute("dt", "urn:schemas-microsoft-com:datatypes", "string")
$child3element1.SetAttribute("dt", "urn:schemas-microsoft-com:xmlns", "urn:schemas-microsoft-com:datatypes")

$child3 = $child2.AppendChild($child3element1)

$child3element1.AppendChild($xml.CreateTextNode("{00000000-0000-0000-0000-000000000000}"))

$xml.Save("c:\xml.xml")

Here is the output I'm getting for the element: 这是我为该元素获得的输出:

<IP_Filter_Template_Guid d9p1:dt="urn:schemas-microsoft-com:datatypes" dt:dt="string" xmlns:d9p1="urn:schemas-microsoft-com:xmlns">

First create the new node as a plain XML node (no namespace manager needed): 首先,将新节点创建为纯XML节点(无需名称空间管理器):

$node = $xml.CreateElement('IP_Filter_Template_Guid')

Create a new attribute node with the desired namespace and assign a value to it: 创建一个具有所需名称空间的新属性节点,并为其分配值:

$ns   = 'urn:schemas-microsoft-com:datatypes'
$attr = $xml.CreateAttribute('dt', 'dt', $ns)
$attr.Value = 'string'

Add the attribute to the XML node using SetAttributeNode() ( not SetAttribute() !): 使用SetAttributeNode()不是 SetAttribute() !)将属性添加到XML节点:

$node.SetAttributeNode($attr)

Demonstration: 示范:

PS C:\> [xml]$xml = '<root/>'
PS C:\> $node = $xml.CreateElement('IP_Filter_Template_Guid')
PS C:\> $ns = 'urn:schemas-microsoft-com:datatypes'
PS C:\> $attr = $xml.CreateAttribute('dt', 'dt', $ns)
PS C:\> $attr.Value = 'string'
PS C:\> $node.SetAttributeNode($attr) >$null
PS C:\> $node.OuterXml
<IP_Filter_Template_Guid dt:dt="string" xmlns:dt="urn:schemas-microsoft-com:datatypes" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM