如何使用 ConvertTo-Xml 和 Select-Xml 加载或读取 XML 文件? [英] How to load or read an XML file using ConvertTo-Xml and Select-Xml?

查看:34
本文介绍了如何使用 ConvertTo-Xml 和 Select-Xml 加载或读取 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能完成这样的事情:

How can I accomplish something like this:

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> $date=(Get-Date | ConvertTo-Xml)                                         
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> $date

xml                            Objects
---                            -------
version="1.0" encoding="utf-8" Objects

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> $date.OuterXml
<?xml version="1.0" encoding="utf-8"?><Objects><Object Type="System.DateTime">12/12/2020 2:43:46 AM</Object></Objects>
PS /home/nicholas/powershell> 

但是,相反,读取文件?

but, instead, reading in a file?

如何使用 ConvertTo-Xml 加载/导入/读取/转换 xml 文件,以便使用 Select-Xml 进行解析>Xpath?

how do I load/import/read/convert an xml file using ConvertTo-Xml for parsing with Select-Xml using Xpath?

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> $xml=ConvertTo-Xml ./bookstore.xml
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> $xml                              

xml                            Objects
---                            -------
version="1.0" encoding="utf-8" Objects

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> $xml.InnerXml                     
<?xml version="1.0" encoding="utf-8"?><Objects><Object Type="System.String">./bookstore.xml</Object></Objects>
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> $xml.OuterXml                     
<?xml version="1.0" encoding="utf-8"?><Objects><Object Type="System.String">./bookstore.xml</Object></Objects>
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> cat ./bookstore.xml

<?xml version="1.0"?>
<!-- A fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
  <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
    <title>Pride And Prejudice</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>24.95</price>
  </book>
  <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>29.95</price>
  </book>
  <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
    <title>Emma</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
    <title>Sense and Sensibility</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
</bookstore>

PS /home/nicholas/powershell> 

REPL 控制台中创建 xml 文件本身按预期工作:

Creating the xml file within the REPL console itself works as expected:

如何使用 Select-Xml 和 Xpath 在 Powershell 中解析 XML?

推荐答案

正确在 Powershell 中读取 XML 文档的工作方式如下:

Properly reading an XML document in Powershell works like this:

$doc = New-Object xml
$doc.Load( (Convert-Path bookstore.xml) )

XML 可以有多种文件编码,并且使用 XmlDocument.Load 方法 确保在不了解编码的情况下正确读取文件.

XML can come in numerous file encodings, and using the XmlDocument.Load method makes sure the file is read properly without prior knowledge of the encoding.

不读取具有正确编码的文件将导致数据损坏或错误,除非在非常基本或非常幸运的情况下.

Not reading a file with the correct encoding will result in mangled data or errors except in very basic or very lucky cases.

使用 Get-Content 并将结果字符串转换为 [xml] 的常见方法正是出于这个原因处理 XML 的错误方法.所以不要那样做.

The often-seen method of using Get-Content and casting the resulting string to [xml] is the wrong way of dealing with XML for this very reason. So don't do that.

您可以使用 Get-Content 获得正确的结果,但这需要

You can get a correct result with Get-Content, but that requires

  1. 事先了解文件编码(例如 Get-Content bookstore.xml -Encoding UTF8)
  2. 将文件编码硬编码到您的脚本中(这意味着如果 XML 编码 永远 意外更改,它将中断)
  3. 仅限于 Get-Content 支持的极少数文件编码(XML 支持更多)
  1. Prior knowledge of the file encoding (e.g. Get-Content bookstore.xml -Encoding UTF8)
  2. Hard-coding the file encoding into your script (meaning it will break if the XML encoding ever changes unexpectedly)
  3. Limiting yourself to the very few file encodings that Get-Content supports (XML supports more)

这意味着您将自己置于必须手动思考和解决 XML 专门为自动处理的问题而设计的位置.

It means you put yourself in a position where you have to manually think about and solve a problem that XML has been specifically designed to automatically handle for you.

使用 Get-Content 正确地做事是很多不必要的额外工作和限制.做正确的事很容易,做错的事毫无意义.

Doing things correctly with Get-Content is a lot of unnecessary extra work and limitations. And doing things incorrectly is pointless when doing it right is so easy.

示例,加载 $doc 后,如上所示.

Examples, after loading $doc like shown above.

$doc.bookstore.book

打印 元素及其属性的列表

prints a list of <book> elements and their properties

genre           : novel
publicationdate : 1997
ISBN            : 1-861001-57-8
title           : Pride And Prejudice
author          : author
price           : 24.95

genre           : novel
publicationdate : 1992
ISBN            : 1-861002-30-1
title           : The Handmaid's Tale
author          : author
price           : 29.95

genre           : novel
publicationdate : 1991
ISBN            : 1-861001-57-6
title           : Emma
author          : author
price           : 19.95

genre           : novel
publicationdate : 1982
ISBN            : 1-861001-45-3
title           : Sense and Sensibility
author          : author
price           : 19.95


$doc.bookstore.book | Format-Table

打印与表格相同的东西

genre publicationdate ISBN          title                 author price
----- --------------- ----          -----                 ------ -----
novel 1997            1-861001-57-8 Pride And Prejudice   author 24.95
novel 1992            1-861002-30-1 The Handmaid's Tale   author 29.95
novel 1991            1-861001-57-6 Emma                  author 19.95
novel 1982            1-861001-45-3 Sense and Sensibility author 19.95


$doc.bookstore.book | Where-Object publicationdate -lt 1992 | Format-Table

过滤数据

genre publicationdate ISBN          title                 author price
----- --------------- ----          -----                 ------ -----
novel 1991            1-861001-57-6 Emma                  author 19.95
novel 1982            1-861001-45-3 Sense and Sensibility author 19.95


$doc.bookstore.book | Where-Object publicationdate -lt 1992 | Sort publicationdate | select title

仅对 </code> 字段进行排序和打印<em class="showen"></em></p> <p class="en">sorts and prints only the <code><title></code> field</p> <pre><code><code>title ----- Sense and Sensibility Emma </code></code></pre> <p class="cn"><hr/><p>对数据进行切片和切块的方法还有很多,这完全取决于您想要做什么.<em class="showen"></em></p> <p class="en"> <hr /> <p>There are many more ways of slicing and dicing the data, it all depends on what you want to do.</p> <p>这篇关于如何使用 ConvertTo-Xml 和 Select-Xml 加载或读取 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!</p> </div> <div class="arc-body-main-more"> <span onclick="unlockarc('2338730');">查看全文</span> </div> </div> <div> </div> <div class="wwads-cn wwads-horizontal" data-id="166" style="max-width:100%;border: 4px solid #666;"></div> </div> </article> <div id="arc-ad-2" class="mb-1"> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5038752844014834" crossorigin="anonymous"></script> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5038752844014834" data-ad-slot="3921941283"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> <div class="widget bgwhite radius-1 mb-1 shadow widget-rel"> <h5>相关文章</h5> <ul> <li> <a target="_blank" title="PowerShell:使用ConvertTo-XML输出的自定义属性XML标记" href="/845946.html"> PowerShell:使用ConvertTo-XML输出的自定义属性XML标记; </a> </li> <li> <a target="_blank" title="如何使用Select-Xml和Xpath解析Powershell中的XML?" href="/2164501.html"> 如何使用Select-Xml和Xpath解析Powershell中的XML?; </a> </li> <li> <a target="_blank" title="如何使用 Select-Xml 和 Xpath 在 Powershell 中解析 XML?" href="/2599048.html"> 如何使用 Select-Xml 和 Xpath 在 Powershell 中解析 XML?; </a> </li> <li> <a target="_blank" title="如何通过 Select-Xml 获取属性值?" href="/2339609.html"> 如何通过 Select-Xml 获取属性值?; </a> </li> <li> <a target="_blank" title="如何在 Powershell 中使用 Select-Xml 打印 xml 节点元素的内容?" href="/2504830.html"> 如何在 Powershell 中使用 Select-Xml 打印 xml 节点元素的内容?; </a> </li> <li> <a target="_blank" title="如何使用 cmdlet Select-Xml 交互式提示?" href="/2504829.html"> 如何使用 cmdlet Select-Xml 交互式提示?; </a> </li> <li> <a target="_blank" title="在 Powershell 中,如何让 Select-Xml 搜索多个节点" href="/2503433.html"> 在 Powershell 中,如何让 Select-Xml 搜索多个节点; </a> </li> <li> <a target="_blank" title="使用open xml读取xml文件" href="/1204614.html"> 使用open xml读取xml文件; </a> </li> <li> <a target="_blank" title="使用javascript或jquery读取Xml文件" href="/1211412.html"> 使用javascript或jquery读取Xml文件; </a> </li> <li> <a target="_blank" title="使用LINQ to XML读取XML" href="/1231983.html"> 使用LINQ to XML读取XML; </a> </li> <li> <a target="_blank" title="How to query XAML file with Powershell&#39;s `select-xml` commandlet?" href="/2928109.html"> How to query XAML file with Powershell&#39;s `select-xml` commandlet?; </a> </li> <li> <a target="_blank" title="如何读取xml文件" href="/1417189.html"> 如何读取xml文件; </a> </li> <li> <a target="_blank" title="如何读取xml文件?" href="/1430436.html"> 如何读取xml文件?; </a> </li> <li> <a target="_blank" title="如何读取xml文件" href="/1366981.html"> 如何读取xml文件; </a> </li> <li> <a target="_blank" title="如何读取xml文件" href="/1330335.html"> 如何读取xml文件; </a> </li> <li> <a target="_blank" title="读取xml文件" href="/1252545.html"> 读取xml文件; </a> </li> <li> <a target="_blank" title="读取XML文件" href="/1299612.html"> 读取XML文件; </a> </li> <li> <a target="_blank" title="Xml文件读取" href="/1311040.html"> Xml文件读取; </a> </li> <li> <a target="_blank" title="如何使用 JAXB 读取 XML 文件?" href="/2839683.html"> 如何使用 JAXB 读取 XML 文件?; </a> </li> <li> <a target="_blank" title="如何使用JAXB读取XML文件?" href="/975289.html"> 如何使用JAXB读取XML文件?; </a> </li> <li> <a target="_blank" title="如何使用Java读取XML文件?" href="/953006.html"> 如何使用Java读取XML文件?; </a> </li> <li> <a target="_blank" title="如何使用EMF读取XML文件?" href="/661058.html"> 如何使用EMF读取XML文件?; </a> </li> <li> <a target="_blank" title="如何使用sax读取xml文件" href="/1442655.html"> 如何使用sax读取xml文件; </a> </li> <li> <a target="_blank" title="使用XML Document读取XML节点" href="/1276158.html"> 使用XML Document读取XML节点; </a> </li> <li> <a target="_blank" title="使用javascript读取xml文件" href="/1024098.html"> 使用javascript读取xml文件; </a> </li> </ul> </div> <div class="mb-1"> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5038752844014834" crossorigin="anonymous"></script> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5038752844014834" data-ad-slot="3921941283"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> <div class="side"> <div class="widget widget-side bgwhite mb-1 shadow"> <h5>其他开发最新文章</h5> <ul> <li> <a target="_blank" title="拒绝显示一个框架,因为它将'X-Frame-Options'设置为'sameorigin'" href="/893060.html"> 拒绝显示一个框架,因为它将'X-Frame-Options'设置为'sameorigin'; </a> </li> <li> <a target="_blank" title="什么是&QUOT; AW&QUOT;在部分标志属性是什么意思?" href="/303988.html"> 什么是&QUOT; AW&QUOT;在部分标志属性是什么意思?; </a> </li> <li> <a target="_blank" title="在运行npm install命令时获取'npm WARN弃用'警告" href="/840917.html"> 在运行npm install命令时获取'npm WARN弃用'警告; </a> </li> <li> <a target="_blank" title="cmake无法找到openssl" href="/516280.html"> cmake无法找到openssl; </a> </li> <li> <a target="_blank" title="从Spark的scala中的* .tar.gz压缩文件中读取HDF5文件" href="/850628.html"> 从Spark的scala中的* .tar.gz压缩文件中读取HDF5文件; </a> </li> <li> <a target="_blank" title="Twitter :: Error :: Forbidden - 无法验证您的凭据" href="/630061.html"> Twitter :: Error :: Forbidden - 无法验证您的凭据; </a> </li> <li> <a target="_blank" title="我什么时候需要一个fb:app_id或者fb:admins?" href="/747981.html"> 我什么时候需要一个fb:app_id或者fb:admins?; </a> </li> <li> <a target="_blank" title="将.db文件导入R" href="/902960.html"> 将.db文件导入R; </a> </li> <li> <a target="_blank" title="npm通知创建一个lockfile作为package-lock.json。你应该提交这个文件" href="/744854.html"> npm通知创建一个lockfile作为package-lock.json。你应该提交这个文件; </a> </li> <li> <a target="_blank" title="拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src'self'”" href="/819167.html"> 拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src'self'”; </a> </li> </ul> </div> <div class="widget widget-side bgwhite mb-1 shadow"> <h5> 热门教程 </h5> <ul> <li> <a target="_blank" title="Java教程" href="/OnLineTutorial/java/index.html"> Java教程 </a> </li> <li> <a target="_blank" title="Apache ANT 教程" href="/OnLineTutorial/ant/index.html"> Apache ANT 教程 </a> </li> <li> <a target="_blank" title="Kali Linux教程" href="/OnLineTutorial/kali_linux/index.html"> Kali Linux教程 </a> </li> <li> <a target="_blank" title="JavaScript教程" href="/OnLineTutorial/javascript/index.html"> JavaScript教程 </a> </li> <li> <a target="_blank" title="JavaFx教程" href="/OnLineTutorial/javafx/index.html"> JavaFx教程 </a> </li> <li> <a target="_blank" title="MFC 教程" href="/OnLineTutorial/mfc/index.html"> MFC 教程 </a> </li> <li> <a target="_blank" title="Apache HTTP客户端教程" href="/OnLineTutorial/apache_httpclient/index.html"> Apache HTTP客户端教程 </a> </li> <li> <a target="_blank" title="Microsoft Visio 教程" href="/OnLineTutorial/microsoft_visio/index.html"> Microsoft Visio 教程 </a> </li> </ul> </div> <div class="widget widget-side bgwhite mb-1 shadow"> <h5> 热门工具 </h5> <ul> <li> <a target="_blank" title="Java 在线工具" href="/Onlinetools/details/4"> Java 在线工具 </a> </li> <li> <a target="_blank" title="C(GCC) 在线工具" href="/Onlinetools/details/6"> C(GCC) 在线工具 </a> </li> <li> <a target="_blank" title="PHP 在线工具" href="/Onlinetools/details/8"> PHP 在线工具 </a> </li> <li> <a target="_blank" title="C# 在线工具" href="/Onlinetools/details/1"> C# 在线工具 </a> </li> <li> <a target="_blank" title="Python 在线工具" href="/Onlinetools/details/5"> Python 在线工具 </a> </li> <li> <a target="_blank" title="MySQL 在线工具" href="/Onlinetools/Dbdetails/33"> MySQL 在线工具 </a> </li> <li> <a target="_blank" title="VB.NET 在线工具" href="/Onlinetools/details/2"> VB.NET 在线工具 </a> </li> <li> <a target="_blank" title="Lua 在线工具" href="/Onlinetools/details/14"> Lua 在线工具 </a> </li> <li> <a target="_blank" title="Oracle 在线工具" href="/Onlinetools/Dbdetails/35"> Oracle 在线工具 </a> </li> <li> <a target="_blank" title="C++(GCC) 在线工具" href="/Onlinetools/details/7"> C++(GCC) 在线工具 </a> </li> <li> <a target="_blank" title="Go 在线工具" href="/Onlinetools/details/20"> Go 在线工具 </a> </li> <li> <a target="_blank" title="Fortran 在线工具" href="/Onlinetools/details/45"> Fortran 在线工具 </a> </li> </ul> </div> </div> </div> <script type="text/javascript">var eskeys = '如何,使用,convertto-xml,和,select-xml,加载,或,读取,xml,文件'; var cat = 'cc';';//other-dev</script> </div> <div id="pop" onclick="pophide();"> <div id="pop_body" onclick="event.stopPropagation();"> <h6 class="flex flex101"> 登录 <span onclick="pophide();">关闭</span> </h6> <div class="pd-1"> <div class="wxtip center"> <span>扫码关注<em>1秒</em>登录</span> </div> <div class="center"> <img id="qr" src="https://huajiakeji.com/Content/Images/qrydx.jpg" alt="" style="width:150px;height:150px;" /> </div> <div style="margin-top:10px;display:flex;justify-content: center;"> <input type="text" placeholder="输入验证码" id="txtcode" autocomplete="off" /> <input id="btngo" type="button" onclick="chk()" value="GO" /> </div> <div class="center" style="margin: 4px; font-size: .8rem; color: #f60;"> 发送“验证码”获取 <em style="padding: 0 .5rem;">|</em> <span style="color: #01a05c;">15天全站免登陆</span> </div> <div id="chkinfo" class="tip"></div> </div> </div> </div> <script type="text/javascript" src="https://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script> <script type="text/javascript" src="https://img01.yuandaxia.cn/Scripts/highlight.min.js"></script> <script type="text/javascript" src="https://img01.yuandaxia.cn/Scripts/base.js?v=0.22"></script> <script type="text/javascript" src="https://img01.yuandaxia.cn/Scripts/tui.js?v=0.11"></script> <footer class="footer"> <div class="container"> <div class="flink mb-1"> 友情链接: <a href="https://www.it1352.com/" target="_blank">IT屋</a> <a href="https://huajiakeji.com/" target="_blank">Chrome插件</a> <a href="https://www.cnplugins.com/" target="_blank">谷歌浏览器插件</a> </div> <section class="copyright-section"> <a href="https://www.it1352.com" title="IT屋-程序员软件开发技术分享社区">IT屋</a> ©2016-2022 <a href="http://www.beian.miit.gov.cn/" target="_blank">琼ICP备2021000895号-1</a> <a href="/sitemap.html" target="_blank" title="站点地图">站点地图</a> <a href="/Home/Tags" target="_blank" title="站点标签">站点标签</a> <a target="_blank" alt="sitemap" href="/sitemap.xml">SiteMap</a> <a href="/1155981.html" title="IT屋-免责申明"><免责申明></a> 本站内容来源互联网,如果侵犯您的权益请联系我们删除. </section> <!--统计代码--> <script type="text/javascript"> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?0c3a090f7b3c4ad458ac1296cb5cc779"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <script type="text/javascript"> (function () { var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> </div> </footer> </body> </html>