如何使用 Powershell 向 XML 檔案新增屬性?
要向 XML 新增屬性,我們首先需要新增元素,然後新增該元素的屬性。
以下是 XML 檔案示例。
示例
<?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> </catalog>
以下命令將新增新元素,但不會儲存檔案。在新增屬性後,我們將儲存檔案。
$file = "C:\Temp\SampleXML.xml" $xmlfile = [xml](Get-Content $file) $newbookelement = $xmlfile.CreateElement("book") $newbookelementadd = $xmlfile.catalog.AppendChild($newbookelement)
要插入屬性並儲存檔案,
$newbookattribute = $newbookelementadd.SetAttribute("id","bk001") $xmlfile.Save($file)
輸出
要新增巢狀元素,或者如果我們需要在新建立的節點下新增屬性,請使用以下程式碼,
示例
$file = "C:\Temp\SampleXML.xml" $xmlfile = [XML](Get-Content $file) $newbooknode = $xmlfile.catalog.AppendChild($xmlfile.CreateElement("book")) $newbooknode.SetAttribute("id","bk102") $newauthorelement = $newbooknode.AppendChild($xmlfile.CreateElement("author")) $newauthorelement.AppendChild($xmlfile.CreateTextNode("Jimmy Welson")) | Out-Null $newtitleelement = $newbooknode.AppendChild($xmlfile.CreateElement("title")) $newtitleelement.AppendChild($xmlfile.CreateTextNode("PowerShell One")) | OutNull $xmlfile.save($file)
輸出
廣告