如何从特定格式的xml读取数据

时间:2019-02-05 08:37:26

标签: c# xml linq

我想使用linq如下读取xml。我想阅读所有元素及其子元素和值以用于我的代码。例如,我想读取ParameterID2及其子元素并显示它们。

<?xml version="1.0" encoding="utf-8"?>
<labelled>
  <historyRecord recordedtime="12/12/1906">
    <ParameterID2>
      <parameterName>SWVersion</parameterName>
      <engineeringUnit>@@@</engineeringUnit>
      <previousValue>R1.2.3</previousValue>
    </ParameterID2>
    <ParameterID3>
      <parameterName>SWVersion</parameterName>
      <engineeringUnit>@@@</engineeringUnit>
      <previousValue>R1.2.3</previousValue>
    </ParameterID3>
    <ParameterID4>
      <parameterName>SWVersion</parameterName>
      <engineeringUnit>@@@</engineeringUnit>
      <previousValue>R1.2.3</previousValue>
    </ParameterID4>
    <ParameterID5>
      <parameterName>SWVersion</parameterName>
      <engineeringUnit>@@@</engineeringUnit>
      <previousValue>R1.2.3</previousValue>
    </ParameterID5>
  </historyRecord>      
</labelled>

我尝试了下面给出的代码。

string xmlDocPath = "C:\\Users\\Dipak\\Desktop\\Documentation.xml";
string timestamp = "12/12/1906"; // this can vary
XDocument xmlDdoc = XDocument.Load(xmlDocPath);
var selectRecord = from recordS in xmlDdoc.Descendants("historyRecord").Where
                               (recordS => (string)recordS.Attribute("recordedtime") == timestamp)
                               select new
                               {
                                   parameterID1 = recordS.Element("ParameterID2").Name,
                                   // parameterID2 = recordS.Element("ParameterID3"),

                                   parameterName = recordS.Element("parameterName").Value,
                                   engineeringUnit = recordS.Element("engineeringUnit").Value,
                                   previousValue = recordS.Element("previousValue").Value,
                               };

0 个答案:

没有答案