将文本添加到XML元素

时间:2016-11-17 22:47:40

标签: xml powershell

我有一个文件,只有一个父元素。

test.xml文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<Data>

</Data>

在另一个文件mytestdata.txt中,我有一些测试数据,如下所示,我想在<Data>标记下添加。

mytestdata.txt的内容

This is my data1
This is my data2
This is my data3

最后输出应为

<?xml version="1.0" encoding="utf-8"?>
<Data>
This is my data1
This is my data2
This is my data3
</Data>

我现在逐个将mytestdata.txt文件的内容转换为变量,现在我想使用

将这些值附加到<Data> </Data>元素中

我应该使用什么函数在<Data>元素下附加这些数据?

2 个答案:

答案 0 :(得分:1)

$xml_text = @'
<?xml version="1.0" encoding="utf-8"?>
<Data>

</Data>
'@

$data_lines = @(
'Data Line 1'
'Data Line 2'
'Data Line 3'
)

$xml = [xml]$xml_text
foreach ($line in $data_lines) {
$xml.Data += $($line + "`r`n")
}

Write-Host -ForegroundColor Green $xml.InnerXml

使用文件:

$xml_text = [System.IO.File]::ReadAllText('file.xml')
$data_lines = [System.IO.File]::ReadLines('file.txt')

UPD01:如果要将一个XML导入另一个XML,则两者都必须是XML

$xml_text1 = @'
<?xml version="1.0" encoding="utf-8"?>
<Data>

</Data>
'@

$xml_text2 = @'
<?xml version="1.0" encoding="utf-8"?>
<rootEl>
    <d1>Val1</d1>
    <d2>Val2</d2>
</rootEl>
'@

$xml1 = [xml]$xml_text1
$xml2 = [xml]$xml_text2
#n is new node. 
#Note that it must be imported as we can add nodes only attached to same document. 
#Note that node is attached to document but not places anywhere yet.
$n = $xml1.ImportNode($xml2.DocumentElement,$true);  #true means we are working with external document

#Place a imported node as document root's child
$xml1.DocumentElement.AppendChild($n) | Out-Null

Write-Host -ForegroundColor Green $xml1.InnerXml
#<?xml version="1.0" encoding="utf-8"?><Data><rootEl><d1>Val1</d1><d2>Val2</d2></rootEl></Data>

答案 1 :(得分:1)

这也将翻译您的特殊字符:

[xml]$xml = Get-Content 'path_to_test.xml'
$xml.Data = (Get-Content 'path_to_mytestdata.txt') -join [System.Environment]::NewLine
$xml.Save('path_to_test.xml')