一般我们遇到的xml的文件都比较简单,没有命名空间的,解析也比较简单,如:
<?xml version="1.0" encoding="utf-8"?>
<xml>
<ID>1</ID>
<Update_Time></Update_Time>
</xml>
建议使用如下方法读取xml文件,防止文件被占用
System.IO.FileStream fs = new FileStream(xml_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
xml.Load(fs);
fs.Close();
fs.Dispose();
解析如下:
string path = ""; //物理路径
XmlDocument xml = new XmlDocument();
xml.Load(path);
xml.SelectSingleNode("xml").SelectSingleNode("Update_Time").InnerText = DateTime.Now.ToString();
xml.Save(filepath); //保存更改
如果遇到带有命名空间的xml(xmlns:xsi)使用上面的办法就无法进行获取,如:
<?xml version="1.0" encoding="utf-8" ?>
<WorkConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.codeplex.com/pangusegment">
<WorkCount>1</WorkCount>
<Result>aaa</Result>
</WorkConfig >
解析代码如下:
//string path = System.AppDomain.CurrentDomain.BaseDirectory + "//config.xml";
string path = ""; // 物理路径
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(path);
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmldoc.NameTable); //namespace
namespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
namespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
namespaceManager.AddNamespace("d","http://www.codeplex.com/pangusegment");
XmlNode node = xmldoc.SelectSingleNode("descendant::d:Result", namespaceManager);
if (node != null)
{
string s = node.InnerText;
}
还有一种不带xmlns:xsi只有xmlns的 如下:
<?xml version='1.0'?>
<bookstore xmlns="urn:newbooks-schema">
<book genre="novel" style="hardcover">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>19.95</price>
</book>
<book genre="novel" style="other">
<title>The Poisonwood Bible</title>
<author>
<first-name>Barbara</first-name>
<last-name>Kingsolver</last-name>
</author>
<price>11.99</price>
</book>
</bookstore>
解析如下:
XmlDocument doc = new XmlDocument();
doc.Load("newbooks.xml");
// Create an XmlNamespaceManager to resolve the default namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");
// Select the first book written by an author whose last name is Atwood.
XmlNode book;
XmlElement root = doc.DocumentElement;
book = root.SelectSingleNode("descendant::bk:book[bk:author/bk:last-name='Atwood']", nsmgr);
本人开发上遇到的,所以记录下来,原文链接是:https://www.cnblogs.com/baylor2019/p/11685995.html
感谢原作者的分享