问题描述
因此,当谈到 powershell 时,我是一个新手,我正在尝试制作一个脚本,该脚本循环遍历 CSV 文件并输出遵循架构的 XML 文件。更具体地说,我试图将每个名称输出到一个文件中,并将其专门放置在用户名位置。最终,如果我能弄清楚这一点,我可以对其他地方做同样的事情。所以我想问题是,如何去做或设置?
示例 XML 架构:
<User>
<Username>mike</Username>
<Password>iamcool</Password>
<Email>mike@mike.com</Email>
<Name>Mike Jones</Name>
<CreationDate>1125442154664</CreationDate>
<ModifiedDate>1125442154664</ModifiedDate>
</User>
解决方法
如果您不需要使用特定的 xml 模式,您可以导入一个 csv,然后使用 ConvertTo-Xml
一次性导出到 xml:
Username,Password,Email
mike,iamcool,mike@mike.com
john,hunter2,john@john.com
# First,we import from a csv,then we can directly export to xml:
$csv = Import-CSV -Path 'c:\path\to\file.csv'
ConvertTo-XML $csv -as String -NoTypeInformation
# Or as one line,exporting to file:
Import-CSV $path | ConvertTo-Xml -as String -NoTypeInformation | Out-File $xmlpath
<?xml version="1.0" encoding="utf-8"?>
<Objects>
<Object>
<Property>
<Property Name="Username">mike</Property>
<Property Name="Password">iamcool</Property>
<Property Name="Email">mike@mike.com</Property>
</Property>
<Property>
<Property Name="Username">john</Property>
<Property Name="Password">hunter2</Property>
<Property Name="Email">john@john.com</Property>
</Property>
</Object>
</Objects>
如果您确实需要匹配现有架构,我会以 .Net 方式进行。例如,尝试匹配您的示例架构:
$csv = Import-Csv 'c:\path\to\file.csv'
# Create an XML object,and give it a declaration line
$xml = [System.Xml.XmlDocument]::new()
$dec = ($xml.CreateXmlDeclaration("1.0","UTF-8",$null))
$root = $xml.DocumentElement
$xml.InsertBefore($dec,$root)
# create main <body> node
$xmlbody = $xml.CreateElement('Body')
$xml.AppendChild($xmlbody)
# import csv to custom nodes
foreach ($user in $csv) {
# create <user> container node
$xmluser = $xml.CreateElement('User')
$xmlbody.AppendChild($xmluser)
# add each property from csv entry to <user>
Foreach ($property in $csv[0].psobject.Properties.name) {
# create a property node
$xmlproperty = $xml.CreateElement($property)
$text = $xml.CreateTextNode($user.$property)
$xmlproperty.AppendChild($text)
# add to current <User> node
$xmluser.AppendChild($xmlproperty)
}
}
# output text
$xml|Format-Xml
# or save to file
$xml.Save('c:\path\to\file.xml')
<?xml version="1.0" encoding="UTF-8"?>
<Body>
<User>
<Username>mike</Username>
<Password>iamcool</Password>
<Email>mike@mike.com</Email>
</User>
<User>
<Username>john</Username>
<Password>hunter2</Password>
<Email>john@john.com</Email>
</User>
</Body>
这两种方法都为您处理特殊字符的编码。