繁体   English   中英

使用LINQ to XML获取自定义属性值

[英]Get custom attribute value using LINQ to XML

我正在写一个XML文件,以后我将从该文件中检索数据。

这是我写入文件的方式。

  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);

这就是将数据写入XML文件后的样子。

<?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>

现在,最简单的方法是获取name属性值(在这种情况下为key2key3 )以及TypeValue属性值。

加载文件;

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

循环读取key节点的内容;

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
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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