我有以下XML:
<UpsHistory>
<UpsSettings>
<Filename>modbusevent.xml</Filename>
<FileDate>04.02.1970</FileDate>
<FileTime>00:05:39</FileTime>
<Type>ENERTRONIC I 3-3 20kVA</Type>
<Location></Location>
<Phases>3</Phases>
<UpsContact>
<Company></Company>
<Department></Department>
<Contact></Contact>
<City></City>
<Street></Street>
<Phone></Phone>
</UpsContact>
</UpsSettings>
<UpsData id="1">
<Date>09.08.2012</Date>
<Time>12:05:53.52</Time>
<EventCode>574</EventCode>
<EventState>A</EventState>
<EventText><![CDATA[IGBT - DRIVERBOARD FAILURE]]></EventText>
<EventAction>/upsexe.cgi?cmd=2003&p1=574&reload=/mbevents.cgi&wait=5</EventAction>
</UpsData>
<UpsData id="2">
<Date>09.08.2012</Date>
<Time>11:23:08.88</Time>
<EventCode>606</EventCode>
<EventState>E</EventState>
<EventText><![CDATA[BYPASS VOLTAGE FAILURE]]></EventText>
<EventAction>/upsexe.cgi?cmd=2003&p1=606&reload=/mbevents.cgi&wait=5</EventAction>
</UpsData>
<UpsData id="3">
<Date>09.08.2012</Date>
<Time>11:23:07.06</Time>
<EventCode>1000</EventCode>
<EventState>E</EventState>
<EventText><![CDATA[CUSTOMER RELAY 1 ON]]></EventText>
<EventAction>/upsexe.cgi?cmd=2003&p1=1000&reload=/mbevents.cgi&wait=5</EventAction>
</UpsData>
<UpsData id="4">
<Date>09.08.2012</Date>
<Time>11:23:06.97</Time>
<EventCode>1003</EventCode>
<EventState>E</EventState>
<EventText><![CDATA[CUSTOMER RELAY 2 OFF]]></EventText>
<EventAction>/upsexe.cgi?cmd=2003&p1=1003&reload=/mbevents.cgi&wait=5</EventAction>
</UpsData>
...
<UpsData id="602">
<Date>08.09.2012</Date>
<Time>11:06:13.84</Time>
<EventCode>606</EventCode>
<EventState>E</EventState>
<EventText><![CDATA[BYPASS VOLTAGE FAILURE]]></EventText>
<EventAction>/upsexe.cgi?cmd=2003&p1=606&reload=/mbevents.cgi&wait=5</EventAction>
</UpsData>
</UpsHistory>
我想获取所有带子元素值的UpsData元素,但我只使用UpsData元素id:
Stream sw = CopyAndClose(response.GetResponseStream());
XmlTextReader rdr = new XmlTextReader(sw);
while (rdr.Read())
{
if (rdr.IsStartElement())
{
if (rdr.NodeType == XmlNodeType.Element)
{
if (rdr.Name == "UpsData")
{
rdr.MoveToAttribute("id");
if (rdr.Name == "Date")
{
ConsoleInfo(rdr.Value);
}
}
}
}
}
我如何获得子元素值?谢谢!
答案 0 :(得分:0)
如果您可以使用XmlDocument或XmlPathNagivator,请考虑使用XPath。例如:
using System.Xml;
...
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
foreach (XmlNode xmlNode in
xmlDocument.DocumentElement.SelectNodes("UpsData/@id[/*]"))
{
// Do something, for example:
Console.Out.WriteLine("Value: " + xmlNode.Value);
}
XPath "UpsData/@id[/*]"
表示查找名为“UpsData”的子节点和具有子节点并返回“id”属性的“id”属性。