1

I am trying to read an XML file which is looking like,

<?xml version="1.0" encoding="UTF-8"?>
<MyXML>
<SESSION FORM_ID="775938" CID="" ID="HAKKI-LAPTOP_634975758376381105">
<FIELD NAME="A001DATE_M" Y="2.32" X="5.5" WIDTH="7.15" HEIGHT="0.99">First Value</FIELD>
<FIELD NAME="A002" Y="2.32" X="17.83" WIDTH="2.38" HEIGHT="0.99">Second Value</FIELD>
<FIELD NAME="A003" Y="1.11" X="17.83" WIDTH="2.38" HEIGHT="0.99">Third Value</FIELD>
<FIELD NAME="A004" Y="1.11" X="5.5" WIDTH="2.38" HEIGHT="0.99">Fourth Value</FIELD>
</SESSION> 
</MyXML>

I am trying to read the read the third value. My Code ables to retrieve the first value.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sXMLPath);
XmlNode node = xmlDoc.SelectSingleNode("MyXML/SESSION/FIELD");
if (node != null)
{
     MessageBox.Show(node.InnerText);
}

What Changes do I need to make in order to read the third or fourth value?

Solution: (Provided by @DGibbs)

XDocument xml = XDocument.Load(sXMLPath);
var elem = (from n in xml.Descendants("FIELD")
            where n.Attribute("NAME").Value == "A004"
            select n).FirstOrDefault();
MessageBox.Show(elem.Value);
4

3 回答 3

5

使用 LINQ to XML 并按NAME属性选择:

XDocument xml = XDocument.Load(fileLocation);

var elem = (from n in xml.Descendants("FIELD")
            where n.Attribute("NAME").Value == "A004"
            select n.Value).FirstOrDefault();

请注意,您需要更新您的 XMLFIELD元素,因为它们是自闭合的并且还具有闭合标签。

例子:

<FIELD NAME="A002" Y="2.32" X="17.83" WIDTH="2.38" HEIGHT="0.99" />Second Value</FIELD>

应该:

<FIELD NAME="A002" Y="2.32" X="17.83" WIDTH="2.38" HEIGHT="0.99">Second Value</FIELD>
于 2013-09-04T12:55:44.547 回答
1

扩展您的XPath选择器[3]

XmlNode node = xmlDoc.SelectSingleNode("MyXML/SESSION/FIELD[3]");
于 2013-09-04T12:53:30.037 回答
1

如果您需要所有字段作为列表,您可以使用DGibbs 答案或尝试这样。,

将所有FIELDS内容放入列表并做任何你想做的事情。,

XDocument xml = XDocument.Load(sXMLPath);

IEnumerable<XElement> elmList = xml.Descendants("FIELD");

foreach (XElement elm in elmList)
{
    // Your Logics goes Here      
}
于 2013-09-04T13:03:37.437 回答