简体   繁体   中英

nested XML parsing in powershell

I am trying to use powershell to parse an XML file to get the value of a specific field. I am running into some issues with getting into the nested objects trying with both Select-XML and [xml]$cn = Get-Content file.xml

I was wondering if anyone would be able to take a look and offer a hand ?

<DentalContainer version="2019-1">
  <Object name="MainObject" type="TDM_Container">
    <Object name="OrderList" type="TDM_List_Order">
      <List name="Items">
        <Object type="TDM_Item_Order">
          <Property name="ClientID" value="91494"/>
          <Property name="ClientOrderNo" value=""/>
          <Property name="ClientContactPerson" value=""/>
          <Property name="OrderImportanceID" value="oiNormal"/>
          <Property name="Patient_RefNo" value=""/>
          <Property name="Patient_FirstName" value=""/>
          <Property name="Patient_LastName" value="testest"/>
          <Property name="DeliveryAddress1" value=""/>
          <Property name="DeliveryAddress2" value=""/>
          <Property name="DeliveryZip" value=""/>
          <Property name="DeliveryCity" value=""/>
          <Property name="DeliveryState" value=""/>
          <Property name="DeliveryCountryID" value=""/>
          <Property name="DeliveryType" value=""/>
          <Property name="ManufName" value="XYZ"/>
          <Property name="OperatorName" value="SIMPLE"/>
        </Object>
      </List>
    </Object>    
    <Property name="ImportForceOverwrite" value="false"/>
    <Property name="ImportForceClean" value="false"/>
    <Property name="EmptyRecycleBin" value="false"/>
  </Object>
</DentalContainer>

Given your xml file, you can use the XPath to look up certain values or properties from it. Since your question is vague, as in what you were interested in, following is a sample on how to access the property attributes (name and value).

[xml]$cn = Get-Content C:\temp\xml.txt

# Single Node
$OrderImportanceID = $cn.DocumentElement.SelectSingleNode("//Property[@name='OrderImportanceID']").Attributes["value"].Value

# All Nodes that match Element with Property tag.
$allProperties = $cn.DocumentElement.SelectNodes("//Property")

# You Can loop all the properties and print each name and value
foreach($prop in $allProperties) {
    Write-output "Property Name: $($prop.Name), Value: $($prop.value)"
}

XPath syntax reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM