代码之家  ›  专栏  ›  技术社区  ›  rickythefox

使用PowerShell加载XML字符串

  •  13
  • rickythefox  · 技术社区  · 15 年前

    我使用

    $str = "<a><b></b></a>"
    

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

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

    我该怎么做?

    3 回复  |  直到 15 年前
        1
  •  23
  •   Cody Gray Felix    6 年前

    你问题中的代码似乎对我有用。我刚加了一句 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

        2
  •  4
  •   brezanac    10 年前

    试试这个

    $xmlcontent = variable which holds xml data in string
    $xml = New-Object -TypeName System.Xml.XmlDocument
    $xml.LoadXml($xmlcontent)
    
        3
  •  4
  •   JsAndDotNet    8 年前

    为了搜索者的利益,如果您有一个包含格式化(而不是在根节点处直接插入)信息的xml顶行,那么您需要在转换它之前删除它的顶行

    例如

    <?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>
    

    要求:

    $xmlFile = Get-Content "*.xml"
    $xmlFileMinusFormatData = $xmlFile[1..($xmlFile.Length - 1)] #we need to remove the first line
    $usableXml = [xml]$xmlFileMinusFormatData # Convert to xml for easy handling
    $usableXml.Courses.CourseEntry.Count # just a count of rows
    
    推荐文章