开发者

select-xml does not return any results

I'm trying to use the powershell command select-xml to select data from an xml file. When I run the command below no results or errors are returned. I expect a list of the editions to be returned to the screen. What's wrong with this?

PS C:\> select-xml -path "C:\t.xml" -xpath "//edition" | foreach {$_.node.InnerXML}
PS C:\>

The XML file (C:\t.xml) is:

 <?xml version="1.0" encoding="utf-8"?>
  <Book>
    <projects>
      <project name="Book1" date="2009-01-20">
        <editions>
           <edition language="English">En.Book1.com</edition>
           <edition language="German">Ge.Book1.Com</edition>
           <edition language="French">Fr.Book1.com</edition>
           <edition language="Polish">Pl.Book1.com</edition>
        </editions>
      </project>
  开发者_如何学Go  </projects>
  </Book>


OK, so I know what's wrong. There was one white space character before the first node of the XML declaration. Really annoying. I tried your first line:

PS H:\> $xml = ([xml](Get-Content -Path C:\scripts\t.xml)).Book.Projects.Project

It errored with:

"..The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it..."

I'm sure that the select-xml should fail in the question with this same error when attempting to read an xml file. The xml file rendered fine in IE.


Just another way to do this is:

PS H:\> $xml = ([xml](Get-Content -Path C:\scripts\t.xml)).Book.Projects.Project
PS H:\> $xml.editions | select -ExpandProperty Edition

language                                                    #text
--------                                                    -----
English                                                     En.Book1.com
German                                                      Ge.Book1.Com
French                                                      Fr.Book1.com
Polish                                                      Pl.Book1.com


$_.node returns a System.Xml.XmlElement which does not have an innerXml property

Select-Xml -Path C:\t.xml -XPath "//edition" | 
    % {$_.node} | get-member | out-gridview


Here's a couple more options:

$xml = [xml]@'
<?xml version="1.0" encoding="utf-8"?>   
<Book>
  <projects>
    <project name="Book1" date="2009-01-20">
      <editions>
        <edition language="English">En.Book1.com</edition>
        <edition language="German">Ge.Book1.Com</edition>
        <edition language="French">Fr.Book1.com</edition>            
        <edition language="Polish">Pl.Book1.com</edition>         
      </editions>       
    </project>     
  </projects>   
</Book> 
'@

$xml | Select-Xml '//edition/text()' | Foreach {"$_"}

$xml | Select-Xml '//edition' |  Foreach {$_.Node.InnerText}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜