C# 加载XML 文件 去掉注释 和命名空间

来源:互联网 发布:mac输入法 编辑:程序博客网 时间:2024/05/16 14:12
static XmlDocument loadXmlFile(string path) {
XmlDocument oldXmlDoc = new XmlDocument();

try {
// remove XML comment <!-- -->
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create(path, settings);
// load old xml doc
oldXmlDoc.Load(reader);

// remove XML ns
string newXml = System.Text.RegularExpressions.Regex.Replace(
oldXmlDoc.OuterXml,
@"(xmlns:?[^=]*=[""][^""]*[""])", "",
System.Text.RegularExpressions.RegexOptions.IgnoreCase |
System.Text.RegularExpressions.RegexOptions.Multiline);

// new xml doc to replace old XmlDoc
doc = new XmlDocument();

doc.LoadXml(newXml);
} catch (System.IO.DirectoryNotFoundException e) {
Console.WriteLine(e.ToString());
doc = null;
} catch (XmlException xmle) {
Console.WriteLine(xmle.ToString());
doc = null;
}
// caught exception, pause
if (doc == null) {
Console.ReadKey();
}

return doc;
}

0 0
原创粉丝点击