Search code examples
windows-runtimelinq-to-xmlxmldocument

Windows Store Apps For each item in a XML file


Can anyone point me in the rigth direction for a solution, to get data from a xml file. I normaly use XmlDocument in VB applications, and that have worked flawless all times.

Now Windows Store Apps not really supporting xmlDocument anymore, som working when DOM is imported but XmlNode is not availble. However maybe its just me but XDocument seems to me to be very very difficult and not very logic for looking up data in a simple XML file.

before i used some like this:

 xmlDevices = xmlDoc.GetElementsByTagName("Device")
 For Each xmlDevice As xmlElement In xmlDevices
  Dim strDeviceName As String = xmlDevice.Item("DeviceName").InnerText

  xmlModbuses = xmlDoc.GetElementsByTagName("Modbus")
  For Each xmlModbus As xmlElement In xmlModbuses
   Dim strModbusID As String = xmlModbus.Attributes("id").InnerText
  Next
 Next

The XML file i wants to seek data from looks like:

<?xml version="1.0" encoding="utf-8" ?>
<Devices>
 <Device id="01">
  <DeviceName>VP18</DeviceName>
  <Modbusees>
   <Modbus id="01">1000</Modbus>
   <Modbus id="02">2000</Modbus>
   ...
  </Modbuses>
  <Alarms>
   <Alarm id="01">
    <AlarmText>Test</AlarmText>
    <AlarmType>Critical</AlarmType>
   </Alarm>
   <Alarm id="02">
    <AlarmText>Test</AlarmText>
    <AlarmType>Critical</AlarmType>
   </Alarm>
  </Alarms>
 <Device id="02">
  <DeviceName>VP19</DeviceName>
   <Modbusees>
    <Modbus id="01">1010</Modbus>
    <Modbus id="02">2020</Modbus>
    ...
  </Modbuses>
  <Alarms>
   <Alarm id="01">
    <AlarmText>Test</AlarmText>
    <AlarmType>Critical</AlarmType>
   </Alarm>
   <Alarm id="02">
    <AlarmText>Test</AlarmText>
    <AlarmType>Critical</AlarmType>
   </Alarm>
  </Alarms>
 </Device>
</Devices>

Best Regards Thomas Nissen


Solution

  • I got it working with following.

            Dim xDoc As XDocument = XDocument.Load(xmlStream.AsStreamForRead())
    
            Dim xmlDevices = xDoc.Root.Elements("Device")
            For Each xmlDevice In xmlDevices
                If xmlDevice.Attribute("id").Value = RoamingSettings.Containers("Device").Values("DeviceID") Then
    
                    Dim xmlAlarms = xmlDevice.Descendants("Alarm")
                    For Each xmlAlarm In xmlAlarms
                        If xmlAlarm.Attribute("id").Value = strAlarmID Then
                            strAlarmDisp = xmlAlarm.Element("AlarmDisp").Value
                            strAlarmType = xmlAlarm.Element("AlarmType").Value
                            strAlarmDesc = xmlAlarm.Element("AlarmDesc").Value
                            strAlarmHelp = xmlAlarm.Element("AlarmHelp").Value
                        End If
                    Next
                End If
            Next