PowerShell XML 架构加载

PowerShell XML schema load

我正在尝试使用 PowerShell 获取 XML 内容,然后将其写入可上传到 SQL 服务器的文本文件。我尝试过的一切都失败了,我发现 XML 在 PowerShell 中有点令人沮丧。

这是我的基本尝试(显示了缩短的路径):

$xmlpath = 'C:\...\GetCourses\Data\GetCourses.xml'
$xsdpath = 'C:\...\GetCourses\Schema\GetCourses.xsd'
$txtpath = 'C:\...\GetCourses\Csv\GetCourses.txt'
[xml]$xmldata = Get-Content $xmlpath
#This is the only thing that gets me anything
$xmldata.GetElementsByTagName("int")
#This does not work
$xmldata.GetCoursesResult.int | Out-File $txtpath -Encoding ascii

这是我从 Visual Studio 中的 XML 文件创建的架构文件的样子:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://www.kmionline.com/elms" attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.kmionline.com/elms" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="GetCoursesResponse">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="GetCoursesResult">
          <xs:complexType>
            <xs:sequence>
              <xs:element maxOccurs="unbounded" name="int" type="xs:unsignedInt" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

如果我手动格式化和简化 XML 文件,使它看起来像 XML,但没有所有名称空间、版本、编码等,那么它就可以正常工作。但是我不能对我生成的每个文件都这样做。我在网上找不到任何有用的东西。请提供任何建议或建议。

这里是 return 响应,为了便于阅读,已截断格式。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetCoursesResponse xmlns="http://www.kmionline.com/elms">
      <GetCoursesResult>
        <int>109</int>
        <int>1000000375</int>
        .
        .
        .
        <int>1000013568</int>
      </GetCoursesResult>
    </GetCoursesResponse>
  </soap:Body>
</soap:Envelope>

使用点访问的优点是您不必处理名称空间管理。但是,您不能遗漏中间节点。要通过点访问从 XML 示例中获取 <int> 节点的值,您需要这样做:

$xmldata.Envelope.Body.GetCoursesResponse.GetCoursesResult.int

如果您想使用正确的 XML 选择方法(提供更大的灵活性),您需要一个名称空间管理器来处理名称空间:

$nm = New-Object Xml.XmlNamespaceManager $xmldata.NameTable
$nm.AddNamespace('ns', 'http://www.kmionline.com/elms')
$xmldata.SelectNodes('//ns:int', $nm)