【发布时间】:2018-04-08 01:32:35
【问题描述】:
我有以下名为 Example.xml 的 XML 文件。请注意根元素 Message 中的命名空间规范 (xmlns),因为下面的问题与此相关。
<?xml version="1.0" encoding="utf-8" ?>
<Message xmlns="http://www.myurl.com/Product" version="010" release="006">
<Header>
<To Qualifier="P" />
<From Qualifier="D" />
<MessageID>f244251a8c6c4070</MessageID>
<SentTime>2018-03-21T22:01:16.70Z</SentTime>
</Header>
<Body>
<Product>
<Description>
<Identification>
<ID1>1871598417</ID1>
<ID2>BE9432042-1234</ID2>
</Identification>
<Type>
<Name>Home Widget</Name>
<Category>Residential</Category>
</Type>
</Description>
</Product>
</Body>
</Message>
我编写了以下函数来使用 LINQ 返回一个字符串
Public Function GetProductDetail() As String
Dim xDoc As XDocument = Nothing
Dim returnValue As String = ""
Using xr As XmlReader = XmlReader.Create("C:\Automation\Example.xml")
xDoc = XDocument.Load(xr)
Dim query = From t In xDoc.Descendants("Body")
Select New With {Key _
.ID1 = t.Element("Product").Element("Description").Element("Identification").Element("ID1").Value,
.ID2 = t.Element("Product").Element("Description").Element("Identification").Element("ID2").Value,
.Name = t.Element("Product").Element("Description").Element("Type").Element("Name").Value}
For Each item In query
returnValue = $"ID1: {item.ID1} | ID2: {item.ID2} | Name: {item.Name}"
Next
End Using
Return returnValue
End Function
我遇到的问题是上述 XML 文件的返回值为空白。
当我将根元素更改为仅如下:
<Message>
(即删除所有内容,包括 xmlns=....)我得到正确的返回值
returnValue = ID1:1871598417 | ID2: BE9432042-1234 |名称:主页小部件
我有以下问题:
当 xmlns 是根元素的一部分时,我需要在代码或 XPath 表达式中添加什么。
有时 XML 文件可能不包含 ID2 元素。如果元素不存在或者这甚至可以使用 LINQ,我如何检查 LINQ 查询。
如果这不适用于 LINQ,有人可以提供有关如何完成此操作的代码。
感谢大家的投入、时间和帮助。
谢谢
朱泽
【问题讨论】:
标签: .net xpath linq-to-xml