我的文件中有以下 xml(简化版):
<?xml version="1.0" encoding="ISO-8859-1"?>
<XCer xmlns="http://x.y.z" xmlns:xsi="http://www.x.y.z" xsi:schemaLocation="http://www.x.y.z" track_id="559" mp_id="398" sub_id="569">
<capability xsi:type="XCracT">
<type>rec</type>
<sub_type>pc</sub_type>
<action>reco</action>
</capability>
<final_result OD="DGS=1.6" creator="Creator1" version="1.11" xsi:type="XCarT">
<code>300000000</code>
<code_cnf>0.7454</code_cnf>
<code_attr>seq</code_attr>
<status_attr>fdos</status_attr>
<text>this text</text>
<standardized_text>other text</standardized_text>
<region>
<type>add</type>
<symbology>machine</symbology>
</region>
</final_result>
<final_result OD="DGS=1.7" creator="Creator2" version="1.11" xsi:type="XCarT">
<code>3040280100015</code>
<code_cnf>0.7454</code_cnf>
<code_attr>seq</code_attr>
<status_attr>fdos</status_attr>
<text>this text</text>
<standardized_text>other text</standardized_text>
<region>
<type>add</type>
<symbology>machine</symbology>
</region>
<polygon>
<dot x="849" y="1600"/>
<dot x="823" y="1600"/>
<dot x="819" y="1166"/>
<dot x="845" y="1166"/>
</polygon>
</final_result>
</XCer>
在非常基础的层面上,我想创建 3 个变量:creator、code、mp_id,并用最终结果 OD="DGS=1.6"部分的详细信息填充它们,即 'Creator1'、'300000000'、'398' (来自第一个 XCer 元素)和“此文本”,但尽管在过去几天尝试了几个速成类(class),但我的 xml 技能非常缺乏。
我已经尝试过基本的
Using reader As XmlReader = XmlReader.Create("C:\filename.xml")
while reader.Read()
if reader.IsStartElement() Then
If reader.Name = "code" Then
code = reader.ReadElementContentAsString()
它为我提供了代码,但我无法获取该行中的任何元素
final_result OD="DGS=1.6"Creator="Creator1"version="1.11"xsi:type="XCarT">
并且我无法将我想要的代码元素限制到该子树而不覆盖以前的代码。
最佳答案
以下是如何使用 XPath 执行此操作的简单示例:
Dim doc As New XmlDocument()
doc.Load("Test.xml")
Dim namespaceManager As New XmlNamespaceManager(doc.NameTable)
namespaceManager.AddNamespace("x", "http://x.y.z")
Dim mp_id As String = doc.SelectSingleNode("/x:XCer[1]/@mp_id", namespaceManager).InnerText
Dim creator As String = doc.SelectSingleNode("/x:XCer[1]/x:final_result[@OD='DGS=1.6']/@creator", namespaceManager).InnerText
Dim code As String = doc.SelectSingleNode("/x:XCer[1]/x:final_result[@OD='DGS=1.6']/x:code", namespaceManager).InnerText
请注意,我需要指定 namespace ,因为所有元素都有一个默认 namespace http://x.y.z
。出于我的目的,我给命名空间添加了 x
前缀,但您可以将其命名为任何您想要的名称。
XPath 是用于查询 XML 文档的标准语言。有些人更喜欢 Microsoft 专有的 LINQ 技术,但由于 XPath 也被其他语言、工具和技术使用,因此非常值得花时间学习它。 SelectSingleNode
和 SelectNodes
方法允许您使用 XPath 查找匹配节点。
第一个 XPath 选择 mp_id
,如下所示:
/x:XCer[1]/@mp_id
/
- 从文档的根目录开始x:XCer
- 查找名为XCer
的元素(在x
命名空间中)[1]
- 仅选择第一个XCer
元素/
- 查找第一个XCer
元素的后代节点@mp_id
- 选择mp_id
属性(它是第一个XCer
元素的后代节点)
下一个选择 creator
属性的 XPath 如下所示:
/x:XCer[1]/x:final_result[@OD='DGS=1.6']/@creator
这一个的开始与上一个相同,但它不是选择 XCer
元素的属性,而是选择 final_result
子元素。 [@OD='DGS=1.6']
是一个条件子句。您可以将其理解为“选择一个 final_result
元素,其 OD
属性等于 DGS=1.6
”。
关于xml - 使用VB.Net解析复杂的xml : elements into strings depending on namespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16481931/