0

In Windows Powershell, I have an XML document which contains an element whose content is text. When an element contains another element, like $x.a in the example below, it is exposed as an element, while the text only child ($x.a.b) is exposed as a string.

PS C:\> $x = [xml]"<a><b>Some Text</b></a>
PS C:\> $x.a -is [Xml.XmlElement]
True
PS C:\> $x.a.b -is [Xml.XmlElement]
False
PS C:\> $x.a.b -is [string]
True

I can understand why this is convenient, but I would like to access b as an XmlElement. Is this possible, and if so, how could I do it?

4

1 回答 1

1

试试GetElementByTagName方法。前任:

$x.a.GetElementsByTagName("b")

#text
-----
Some Text

$x.a.GetElementsByTagName("b").gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
False    False    XmlElementList                           System.Xml.XmlNodeList


$x.a.GetElementsByTagName("b")[0].gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    XmlElement                               System.Xml.XmlLinkedNode

或者如果您愿意,可以使用 xpath:

$x.a.SelectSingleNode("b")

#text
-----
Some Text

$x.a.SelectSingleNode("b").gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    XmlElement                               System.Xml.XmlLinkedNode
于 2013-05-18T10:17:52.203 回答