我正在尝试使用 PowerShell 创建一个 xml 文档,我的问题是已附加到父级的元素不会继承声明命名空间前缀,但是在尝试时,我设法让它具有前缀,但仅包含另一个 xmlns=""。
$UserName = $env:UserName
$OutputPath = "C:\Users\" + $UserName +"\Desktop\Generator\Output\"
$OutputXML = $OutputPath + "Test_File_1.xml"
#Namespace URIs
$VQ5NSX = "http://example2"
$VQ5INTX ="http://example1"
[xml]$Doc = New-Object System.Xml.XmlDocument
$dec = $Doc.CreateXmlDeclaration("1.0","UTF-8",$null)
$doc.AppendChild($dec)
$root = $doc.CreateNode("element","ns:responsefile", $VQ5NSX)
$int = $doc.CreateNode("element", "int:IntegrationHeader",$VQ5INTX)
$IntDt = $doc.CreateElement("int:Date",$null)
$IntDt.InnerText = "Date Text"
$Int.AppendChild($IntDt) | Out-Null
$IntId = $doc.CreateElement("Identification")
$IntAppID = $doc.CreateElement("ApplicationId")
$IntAppIDtxt = $Doc.CreateTextNode("App Id Text")
$IntAppId.AppendChild($IntAppIDtxt)|Out-Null
$IntId.AppendChild($IntAppID)|Out-Null
$IntTransID = $doc.CreateElement("TransactionId")
$IntTransIDtxt = $Doc.CreateTextNode("Tran Id Text")
$IntTransID.AppendChild($IntTransIDtxt) |Out-Null
$IntId.AppendChild($IntTransID) |Out-Null
$Int.AppendChild($IntId) |Out-Null
$root.AppendChild($int)|Out-Null
$Res = $doc.CreateNode("element","ns:ResponseItem", $null)
$ItemDetail = $doc.CreateElement("ns:Item1")
$ItemDetail = $doc.CreateTextNode("Item one text")
$Res.AppendChild($ItemDetail)|Out-Null
$root.AppendChild($res)|Out-Null
$doc.AppendChild($root) |Out-Null
$doc.save($OutputXML)
这会生成以下输出;
<?xml version="1.0" encoding="UTF-8"?>
<ns:responsefile xmlns:ns="http://example2">
<int:IntegrationHeader xmlns:int="http://example1">
<Date>Date Text</Date>
<Identification>
<ApplicationId>App Id Text</ApplicationId>
<TransactionId>Tran Id Text</TransactionId>
</Identification>
</int:IntegrationHeader>
<ResponseItem>Item one text</ResponseItem>
</ns:responsefile>
但是我需要它来生成此输出;
<?xml version="1.0" encoding="UTF-8"?>
<ns:responsefile xmlns:ns="http://example2">
<int:IntegrationHeader xmlns:int="http://example1">
<int:Date>Date Text</Date>
<int:Identification>
<int:ApplicationId>App Id Text</int:ApplicationId>
<int:TransactionId>Tran Id Text</int:TransactionId>
</int:Identification>
</int:IntegrationHeader>
<ns:ResponseItem>Item one text</ns:ResponseItem>
</ns:responsefile>
任何帮助将不胜感激!
最佳答案
尽 pipe 节点可以继承前缀的定义,但每个子节点仍然需要在该命名空间中指定。
目前,您明确请求 <Date>
元素不在任何命名空间中:
$doc.CreateElement("int:Date",$null)
.net 类假设您输入 int:
错误地进入,因为没有命名空间的元素没有前缀。
相反,您需要指定 <Date>
元素位于http://example1
中命名空间:
$doc.CreateElement("int:Date",$VQ5INTX)
如果实现很聪明,它会注意到前缀 int
已绑定(bind)到该命名空间,并避免重复 xmlns:int
属性(这会很困惑,但不会显着改变文档)。
关于xml - 在 PowerShell 中创建从父节点继承命名空间前缀的 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48284287/