我正在写一个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
属性值(在这种情况下为key2和key3)以及Type
和Value
属性值。
加载文件;
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
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句