简体   繁体   中英

Get custom attribute value using LINQ to XML

I'm writing to an XML file from which I'm going to retrieve data later.

Here's how I'm writing to the file.

  XNamespace testNM = "urn:lst-emp:emp";
                XDocument xDoc;
                string path = "project_data.xml";
                if (!File.Exists(path))
                {
                    xDoc = new XDocument(
                               new XDeclaration("1.0", "UTF-16", null),
                               new XElement(testNM + "Test")
                               );
                }
                else
                {
                    xDoc = XDocument.Load(path);
                }

                var element = new XElement("key",
                        new XAttribute("name", key),
                        new XElement("Type", type),
                        new XElement("Value", value));

                xDoc.Element(testNM + "Test").Add(element);

                // Save to Disk
                xDoc.Save(path);

And this is what my XML file looks like after data is written to it.

<?xml version="1.0" encoding="utf-16"?>
<Test xmlns="urn:lst-emp:emp">
  <key name="key2" xmlns="">
    <Type>int</Type>
    <Value>12312</Value>
  </key>
  <key name="key3" xmlns="">
    <Type>String</Type>
    <Value>asdfasd</Value>
  </key>
</Test>

Now what would be the simplest way to get the name attribute value ( key2 and key3 in this case) along with the Type and Value attribute values.

Load the document;

XDocument doc = XDocument.Load(@"doc.xml");

Loop the key nodes reading what you need;

foreach (var keyNode in doc.Root.Elements("key"))
{
    var name = keyNode.Attribute("name");
    var type = (string)keyNode.Element("Type"); // or .value to throw if there is no node
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM