使用PowerShell加载XML字符串

时间:2010-10-14 16:29:30

标签: xml powershell

我已经使用

定义了一个XML字符串
$str = "<a><b></b></a>"

现在我想将它加载到[xml]变量中,以便能够操纵它的节点等。 下面的行会导致错误...

$str = [xml]"<a><b></b></a>"

我该怎么做?

3 个答案:

答案 0 :(得分:22)

我发现这篇文章非常好:http://www.pluralsight-training.net/community/blogs/dan/archive/2006/11/25/42506.aspx

这一个:http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-14-xml.aspx

何时需要在PowerShell中处理XML


你的问题似乎对我有用。你发布错误怎么样,我们可以看到发生了什么?我刚刚在我的字符串中添加test以显示我可以访问该值,但它也应该没有它。

Yes I added test, but you can see my example worked Full Image


另一个编辑:

施放字符串也对我有用,所以你怎么样向我们展示一些工作,因为我无法重现你的问题 Again, I added test to show that I can access XML members Full Image


...我用你的字符串运行它,它工作得很好...... ...notice there was an empty return? Full Image

答案 1 :(得分:3)

试试这个

$xmlcontent = variable which holds xml data in string
$xml = New-Object -TypeName System.Xml.XmlDocument
$xml.LoadXml($xmlcontent)

答案 2 :(得分:3)

为了搜索者的利益,如果您的xml顶行包含格式(而不是直接在根节点处)信息,则需要先删除顶行才能进行投射

e.g。

ion-segment-button

需要:

<?xml version="1.0" encoding="utf-8"?>
<Courses>
  <CourseEntry Type="Mandatory" Name="Math"/>
  <CourseEntry Type="Mandatory" Name="Coding" />
  <CourseEntry Type="Optional" Name="Economics" />
  <CourseEntry Type="Optional" Name="History" />
</Courses>