正如評論所說,您可以將您的文件轉換爲實時XML類型,並對其進行操作,像這樣:
# In you case, you would load it from a file with Get-Content
$XmlString = @'
<?xml version="1.0"?>
<content>
<areas>
<area1>
some text
more lines
when does it end?
</area1>
<area2>
uninteresting text
</area2>
<area3>
more of it
</area3>
</areas>
</content>
'@
# Create an XmlDocument object from the string input
$XmlDoc = [xml]$XmlString
# Select the area1 node with XPath
$area1 = $XmlDoc.SelectSingleNode('//area1')
# Set the inner text value to an empty string:
$area1.'#text' = ''
# Save the document
$XmlDoc.Save("C:\path\to\file.xml")
XPath表達式//area1
將找到標記名稱爲「area1」的任何節點。 如果在文檔中不止一個,你可以指定完整路徑,而不是:
$area1 = $XmlDoc.SelectSingleNode('/content/areas/area1')
您可以將字符串轉換爲XML數據類型,並指定你要尋找的元素,無論是與XPath查詢或者只是點引用。只有當元素是獨特的名稱或者以獨特的順序時,它纔會有效,但通常它運行得很好。 –