英文:
How to add multiple attribute and corresponding values within xml child node
问题
要向XML子节点添加多个属性和值。
例如,我想在Namespace元素内添加另一个Rule。
<GlobalAppSettings>
<NameSpace name="retail">
</NameSpace>
<NameSpace name="APEService" inheritsFrom="retail">
<Rules>
<Rule namespace="retail" queues="Default" scanInterval="10000" threads="2" />
<Rule namespace="retail" queues="DLS" scanInterval="9000" threads="1" />
<!-- 在这里添加另一个Rule -->
</Rules>
</NameSpace>
</GlobalAppSettings>
我尝试添加另一个元素和文本节点,但卡在这一点上,无法继续。
英文:
Add multiple attributes and values to a xml child node.
Ex- I want to add another Rule within Namespace element.
<GlobalAppSettings
<NameSpace name="retail"
</NameSpace>
<NameSpace name="APEService" inheritsFrom="retail">
<Rules>
<Rule namespace="retail" queues="Default" scanInterval="10000" threads="2" />
<Rule namespace="retail" queues="DLS" scanInterval="9000" threads="1" />
</Rules>
</NameSpace>
</GlobalAppSettings>
I tried adding another element and a text node but am stuck at this point and unable to proceed.
答案1
得分: 1
您可以使用System.Xml.XmlDocument
来完成这个操作。
以下是如何向您提到的 XML 添加额外规则的示例:
$pathToXml = "C:\temp\xml.xml"
$xml = New-Object System.Xml.XmlDocument
$xml.Load($pathToXml)
$namespaceNode = $xml.SelectSingleNode("//NameSpace[@name='APEService']")
$rulesNode = $namespaceNode.SelectSingleNode("Rules")
# 添加新规则:
$ruleNode = $xml.CreateElement("Rule")
$ruleNode.SetAttribute("namespace", "retail")
$ruleNode.SetAttribute("queues", "sometimes")
$ruleNode.SetAttribute("scanInterval", "8000")
$ruleNode.SetAttribute("threads", "2")
$rulesNode.AppendChild($ruleNode)
# 移除规则:
# 通过队列名选择要移除的规则
# 如果需要移除整个命名空间,可以使用@namespace而不是@queues
$ruleToRemove = $rulesNode.SelectSingleNode("Rule[@queues='DLS']")
# 从父节点中移除规则
$rulesNode.RemoveChild($ruleToRemove)
$xml.Save($pathToXml)
英文:
You can use the
System.Xml.XmlDocument
to accomplice this
here is an example of how to add an extra rule to your mentioned xml
$pathToXml = "C:\temp\xml.xml"
$xml = New-Object System.Xml.XmlDocument
$xml.Load($pathToXml)
$namespaceNode = $xml.SelectSingleNode("//NameSpace[@name='APEService']")
$rulesNode = $namespaceNode.SelectSingleNode("Rules")
# Adding a new rule:
$ruleNode = $xml.CreateElement("Rule")
$ruleNode.SetAttribute("namespace", "retail")
$ruleNode.SetAttribute("queues", "sometimes")
$ruleNode.SetAttribute("scanInterval", "8000")
$ruleNode.SetAttribute("threads", "2")
$rulesNode.AppendChild($ruleNode)
# Removing a rule:
# Select the rule to be removed by the queues name
# if you need to remove a complete namespace you could just use @namespace instead of @queues
$ruleToRemove = $rulesNode.SelectSingleNode("Rule[@queues='DLS']")
# Remove the rule from the parent node
$rulesNode.RemoveChild($ruleToRemove)
$xml.Save($pathToXml)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论