简体   繁体   中英

How do I get a specific XML node in Powershell

I have an XML in powershell below:

[Xml]$MyXmlVariable = @"
<Mylist>
  <Item Number="1">
    <Name>"AMD Ryzen 5 3600x"</Name>
    <Type>"CPU"</Type>
    <Price>"$169.99"</Price>
    <Where>"Amazon"</Where>
    <Other>
      <ThreadCount>"12"</ThreadCount>
      <Cores>"6"</Cores>
    </Other>
  </Item>
</MyList>
"@

And it looks fne to me, but when I try to define it, I get the error

Cannot convert value "<Mylist>
  <Item Number="1">
    <Name>"AMD Ryzen 5 3600x"</Name>
    <Type>"CPU"</Type>
    <Price>".99"</Price>
    <Where>"Amazon"</Where>
    <Other>
      <ThreadCount>"12"</ThreadCount>
      <Cores>"6"</Cores>
    </Other>
  </Item>
</MyList>" to type "System.Xml.XmlDocument". Error: "The 'Mylist' start tag on line 1
position 2 does not match the end tag of 'MyList'. Line 12, position 3."
At line:1 char:1
+ [Xml]$MyXmlVariable = @"
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataExcepti
   on
    + FullyQualifiedErrorId : RuntimeException

AFAIK there doesn't seem to be an error but Powershell says otherwise. Please Help

XMLs are case-sensitive so an XML like this:

<test></Test>

Will also not work having the error

Cannot convert value "<test></Test>" to type "System.Xml.XmlDocument". Error: "The 'test'
start tag on line 1 position 2 does not match the end tag of 'Test'. Line 1, position 9."
At line:1 char:1
+ [xml]"<test></Test>"
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastToXmlDocument

In your XML, the starting and ending tags are different:

[Xml]@"
<Mylist>
<!--l is not capitalized-->
  <Item Number="1">
    <Name>"AMD Ryzen 5 3600x"</Name>
    <Type>"CPU"</Type>
    <Price>"$169.99"</Price>
    <Where>"Amazon"</Where>
    <Other>
      <ThreadCount>"12"</ThreadCount>
      <Cores>"6"</Cores>
    </Other>
  </Item>
</MyList>
<!--l is capitalized-->
"@

Which means that <Mylist> and </MyList> are two different nodes.

This is what is causing your error so try

[Xml]$MyXmlVariable = @"
<MyList>
  <Item Number="1">
    <Name>"AMD Ryzen 5 3600x"</Name>
    <Type>"CPU"</Type>
    <Price>"$169.99"</Price>
    <Where>"Amazon"</Where>
    <Other>
      <ThreadCount>"12"</ThreadCount>
      <Cores>"6"</Cores>
    </Other>
  </Item>
</MyList>
"@

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