我正在 xml 文件中搜索特定元素,我想出了一个不错的解决方案,它将找到我需要的元素,但是,如果我要打开 Option Strict,编译器会告诉我它没有不允许后期绑定(bind)。在互联网上的快速搜索使我发现绑定(bind)需要在执行之前初始化为类型,只是不确定如何进行。
我可以简单地关闭该选项,但为了更好地编码,我想保留它并看看如何避免后期绑定(bind)。老实说,我不确定从哪里开始,我是否需要一个具有自己属性的类?
Dim xmlDocument As String = "C:\***\comp.xml" ' Path '
Dim xelement As XDocument = XDocument.Load(xmlDocument)
Console.WriteLine("What company are you searching for? ")
searchCompData = Console.ReadLine()
Dim results As IEnumerable(Of Object) = From c In xelement.Descendants("COMPANYINFO").Descendants("Office")
Where CType(c.Parent.Parent.Element("compId"), String) = searchCompData
Select New With
{
.reg = c.Parent.Element("Region"),
.city = c.Parent.Element("City"),
.ceo = c.Parent.Element("CEO"),
.office = c
}
For Each res As Object In results
Console.WriteLine(res.reg)
Console.WriteLine(res.city)
Console.WriteLine(res.ceo)
Console.WriteLine(res.office)
Next
Console.ReadLine()
我的示例 xml 文件
<?xml version="1.0" encoding="utf-8"?>
<CompType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyRegion>
<compId>1</compId>
<compRegionId>654</compRegionId>
<compTransPort>Van</compTransPort>
<COMPANYINFO>
<compInfoId>545</compInfoId>
<City>London</City>
<Zip>3214</Zip>
<Zone>535</Zone>
<Region>London Region</Region>
<LocalNumber>54687874</LocalNumber>
<CEO>Alice Goldsmith</CEO>
<CompanyStreet>BongoBingo St</CompanyStreet>
<Office>
<Name>IT</Name>
<Place>2nd Floor</Place>
<Manager>
<Name>Steven Smith</Name>
<Address>Robo Street</Address>
<Phonenumber>12345</Phonenumber>
</Manager>
</Office>
<Office>
<Name>Accountants</Name>
<Place>3d Floor</Place>
<Manager>
<Name>Joana Petersen</Name>
<Address>Lamba Street</Address>
<Phonenumber>54321</Phonenumber>
</Manager>
</Office>
</COMPANYINFO>
</CompanyRegion>
<CompanyRegion>
<compId>2</compId>
<compRegionId>785</compRegionId>
<compTransPort>Truck</compTransPort>
<COMPANYINFO>
<compInfoId>321</compInfoId>
<City>Oslo</City>
<Zip>4598</Zip>
<Zone />
<Region>Oslo Region</Region>
<LocalNumber>458754121</LocalNumber>
<CEO>Michael Jonson</CEO>
<CompanyStreet>BingoBango St</CompanyStreet>
<Office>
<Name>Sales</Name>
<Place>4th Floor</Place>
<Manager>
<Name>Rachel Laurensen</Name>
<Address>Albo Street</Address>
<Phonenumber>55555</Phonenumber>
</Manager>
</Office>
<Office>
<Name>Accountants</Name>
<Place>1st Floor</Place>
<Manager>
<Name>Peter Carlsen</Name>
<Address>Lobo Street</Address>
<Phonenumber>455656</Phonenumber>
</Manager>
</Office>
</COMPANYINFO>
</CompanyRegion>
</CompType>
最佳答案
可以删除
As IEnumerable(Of Object)
来推断匿名类型,并且需要 .Value
来获取元素值。另外,VB.Net XML axis properties可用于简化查询:
Dim results = From c In xelement...<CompanyRegion>
Where c.<compId>.Value = searchCompData
Select New With {
.reg = c...<Region>.Value,
.city = c...<City>.Value,
.ceo = c...<CEO>.Value,
.office = c...<Office>
}
关于xml 到 linq,如何修复后期绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57217071/