powershell - 如何通过 Powershell 将 XML-Data 读入数据表并通过给定的 XmlSchema 强制使用正确的类型?
问题描述
我目前正在努力通过强制执行给定的 XmlSchema 将 XMLdata 读入数据表。无论我做什么,在数据导入之后,所有类型都设置回“字符串”。我需要强制以下 ID 列的类型为“int”(不是“string”或“byte”):
$schema = '
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:group name="r">
<xs:sequence>
<xs:element name="id" type="xs:int" />
<xs:element name="name" type="xs:string" />
</xs:sequence>
</xs:group>
<xs:complexType name="body">
<xs:group ref="r" />
</xs:complexType>
</xs:schema>'
$data = '
<body>
<r>
<id>9</id>
<name>AAA</name>
</r>
<r>
<id>10</id>
<name>BBB</name>
</r>
</body>'
# read the schema:
$set = [System.Data.Dataset]::new()
$sr =[System.IO.StringReader]::new($schema)
$set.ReadXmlSchema($sr)
# read the data:
$sr =[System.IO.StringReader]::new($data)
$set.ReadXml($sr)
cls
$set.Tables | ft -AutoSize
write-host "type of column 'id' in table : " $set.Tables[0].Columns[0].DataType
$list = [System.Collections.ArrayList]::new($set.Tables[0].GetList())
write-host "type of column 'id' in list : " $list[0].id.GetType()
我还对 XMLReadMode 进行了一些测试,但是当我使用 [System.Data.XmlReadMode]::InferTypedSchema 时,会出现唯一的变化,但这会根据该列的数据将类型更改为“字节”或其他内容。
任何帮助都非常受欢迎!提前谢谢你。
解决方案
感谢提示,我终于解决了。首先我发现,我不需要在数据导入之前创建专用的 XMLSchema - 只需创建正确的表结构就可以用更少的代码做同样的事情。
这是最终的代码示例:
cls
$set =[System.Data.DataSet]::new()
$set.tables.Add('r')
$table = $set.Tables[0]
[void]$table.Columns.Add('id', [int])
[void]$table.Columns.Add('name', [string])
$data = '
<body>
<r>
<id>9</id>
<name>AAA</name>
</r>
<r>
<id>10</id>
<name>BBB</name>
</r>
</body>'
# read the data:
$sr =[System.IO.StringReader]::new($data)
[void]$set.ReadXml($sr)
$set.Tables | ft -AutoSize
write-host "type of column 'id' in table : " $table.Columns['id'].DataType
$list = [System.Collections.ArrayList]::new($table.GetList())
write-host "type of column 'id' in list : " $list[0].id.GetType()
这里是上面脚本的输出:
id name
-- ----
9 AAA
10 BBB
type of column 'id' in table : System.Int32
type of column 'id' in list : System.Int32
推荐阅读
- javascript - 将工具提示添加到禁用的 Dropdown.Toggle
- javascript - 带有 webpack require() 的 Vue.js 动态图像 src 不起作用
- javascript - 从高级语言编译到低级语言
- paypal - 在哪里输入 paypal IPN url 以及如何传递自定义数据?
- regex - 如何为下降递归解析器 LL(1) 编写 nextToken() 函数
- laravel - 当以用户身份登录时,buefy 停止使用 Vue 在 Laravel 中工作
- python - Tkinter Canvas:更改选项而不更改其他选项或再次设置所有选项
- r - 过滤掉R中包含UTF-8阿拉伯字符的列中的条目
- javascript - Cookie 不会存储在本地主机中
- list - `eval` 的第一个参数必须是一个列表吗?