好的,我有一个提供的自定义XML字符串,因此无法修改结构,它是一个键值对,如此处所示
<?xml version='1.0' encoding='utf-8'?>
<ContentStack ID='13' Type='11'>
<ContentElement1 ID='11' Type='IMAGE'>
<Key AttributeName='Name' AttributeValue='SOMENAME'></Key>
<Key AttributeName='SRC' AttributeValue='SOMEFILE.jpg'></Key>
<Key AttributeName='ALT' AttributeValue='SOMEALT'></Key>
<Key AttributeName='Class' AttributeValue='SOMECLASS'></Key>
</ContentElement1>
</ContentStack>
我希望能够抓住attribute value
并将它们分配给变量,所以我最终会得到类似的结果。
Dim thsValueOne AS String = "SOMENAME"
Dim thsValueTwo AS String = "SOMEFILE.jpg"
Dim thsValueThree AS String = "SOMEALT"
Dim thsValueFour AS String = "SOMECLASS"
我尝试过这样做但没有运气
Dim xDoc As XDocument = XDocument.Parse(" MY XML STING IN HERE ")
thsValueOne = xDoc.Descendants("Key.AttributeValue").Skip(0).Take(1).ToString
我想我不在附近。
答案 0 :(得分:0)
好的,能够根据问题得出这个基于XML的答案很简单
Dim xDoc As XDocument = XDocument.Parse(thsXmlContent)
thsValueOne = xDoc.Root.Descendants.<Key>(0).@AttributeValue
thsValueTwo = xDoc.Root.Descendants.<Key>(1).@AttributeValue
thsValueThree = xDoc.Root.Descendants.<Key>(2).@AttributeValue
thsValueFour = xDoc.Root.Descendants.<Key>(3).@AttributeValue
答案 1 :(得分:0)
您可以尝试以下任何一种解决方法,以便了解这一概念。
当您使用VB.NET时,您可以使用XML文字:
Private Sub test1()
Dim xFrag = <?xml version='1.0' encoding='utf-8'?>
<ContentStack ID='13' Type='11'>
<ContentElement1 ID='11' Type='IMAGE'>
<Key AttributeName='Name' AttributeValue='SOMENAME'></Key>
<Key AttributeName='SRC' AttributeValue='SOMEFILE.jpg'></Key>
<Key AttributeName='ALT' AttributeValue='SOMEALT'></Key>
<Key AttributeName='Class' AttributeValue='SOMECLASS'></Key>
</ContentElement1>
</ContentStack>
Dim query = xFrag...<Key>, pos& = 0
For Each ele As XElement In query
pos += 1
MsgBox(String.Format("Test1:Key({0}):AttributeName='{1}' AttributeValue='{2}'", pos.ToString, ele.@AttributeName, ele.@AttributeValue))
Next ele
End Sub
或以其他方式使用Parse
方法。
Private Sub test2()
Dim xStr = "<?xml version='1.0' encoding='utf-8'?><ContentStack ID='13' Type='11'><ContentElement1 ID='11' Type='IMAGE'><Key AttributeName='Name' AttributeValue='SOMENAME'></Key><Key AttributeName='SRC' AttributeValue='SOMEFILE.jpg'></Key><Key AttributeName='ALT' AttributeValue='SOMEALT'></Key><Key AttributeName='Class' AttributeValue='SOMECLASS'></Key></ContentElement1></ContentStack>"
Dim xFrag = XDocument.Parse(xStr)
Dim query = xFrag...<Key>, pos& = 0
For Each ele As XElement In query
pos += 1
MsgBox(String.Format("Test2:Key({0}):AttributeName='{1}' AttributeValue='{2}'", pos.ToString, ele.@AttributeName, ele.@AttributeValue))
Next ele
End Sub
希望这会有所帮助......