问题
I have a puzzling situation with a CDATA string from XML I am accessing.
I am access an XML API and collecting the CDATA string in PowerShell. It returns like this:
aggressorAllianceID: 99006227 aggressorCorpID: 244898283 aggressorID: 1283793762 armorValue: 1.0 hullValue: 1.0 moonID: 40043321 shieldValue: 0.5166110755741394 solarSystemID: 30000686 typeID: 20060
As you can see there are multiple lines. I want to collect this to variables so for example $aggressorAllianceID = 99006227
.
The full XML is here:
<eveapi version="2">
<currentTime>2017-07-19 09:08:18</currentTime>
<result>
<rowset name="notifications" key="notificationID" columns="notificationID">
<row notificationID="644139237">
<![CDATA[
aggressorAllianceID: 99006227 aggressorCorpID: 244898283 aggressorID: 1283793762 armorValue: 1.0 hullValue: 1.0 moonID: 40043321 shieldValue: 0.5166110755741394 solarSystemID: 30000686 typeID: 20060
]]>
</row>
</rowset>
</result>
<cachedUntil>2027-07-17 09:08:18</cachedUntil>
</eveapi>
I have tryed to parse the CDATA string with the split command but I'm not really getting awhere?
Can anyone provide me an example of how they would access and variable this CDATA information?
回答1:
The canonical way of storing data like that is a hashtable. Use the ConvertFrom-StringData cmdlet for transforming a list of key=value pairs in a string to a hashtable data structure. Since your data has colons instead of =
you need to replace them first.
$cdata = @'
aggressorAllianceID: 99006227
aggressorCorpID: 244898283
aggressorID: 1283793762
armorValue: 1.0
hullValue: 1.0
moonID: 40043321
shieldValue: 0.5166110755741394
solarSystemID: 30000686
typeID: 20060
'@
$ht = $cdata -replace ':', '=' | ConvertFrom-StringData
Then you can access the individual values like this:
$ht['aggressorID']
$ht['hullValue']
...
回答2:
Undeleted due to Tomalak's helpful comments - please read before considering New-Variable
Ansgar's answer is a better way to store this data and deal with this programmatically. To answer your literal question of how to get, for example $aggressorAllianceID = 99006227
, you can use New-Variable
input.txt
aggressorAllianceID: 99006227
aggressorCorpID: 244898283
aggressorID: 1283793762
armorValue: 1.0
hullValue: 1.0
moonID: 40043321
shieldValue: 0.5166110755741394
solarSystemID: 30000686
typeID: 20060
$myReturnedValues = Get-content .\input.txt
foreach($line in $myReturnedValues){
New-Variable -Name ($line.Split(": "))[0] -Value ($line.Split(": "))[2]
}
来源:https://stackoverflow.com/questions/45186049/how-to-get-values-in-cdata-in-xml-file-with-powershell