XML工具类

using System; using System.Collections; using System.IO; using System.Text; using System.Xml; namespace OA.SystemFramework { /// /// XML工具. /// public class XmlToolkit { /// /// 读取XML节. /// /// 文件名. /// 文件路径. /// XML字符串. public static string ReadFregment( string file, string path ) { string LastElement = Path.GetFileName( path ); ArrayList list = new ArrayList(); XmlTextReader reader = new XmlTextReader( file ); while( reader.Read() ) { bool needRemove = false; if( reader.NodeType == XmlNodeType.Element ) { list.Add( reader.Name ); if( reader.IsEmptyElement ) { needRemove = true; } } else if( reader.NodeType == XmlNodeType.EndElement ) { needRemove = true; } #if DEBUG Console.WriteLine( "XmlToolkit:遍历Path:" + Toolkit.Array2String( list, "//" ) ); #endif if( reader.Name == LastElement ) { string currentPath = Toolkit.Array2String( list, "//" ); #if DEBUG Console.WriteLine( "XmlToolkit:比较Path:" + currentPath ); #endif if( currentPath == path + "//" ) { string fregment = reader.ReadOuterXml(); #if DEBUG Console.WriteLine( "节点值:" + fregment ); #endif reader.Close(); return fregment; } } if( needRemove ) { list.RemoveAt( list.Count - 1 ); } } reader.Close(); return ""; } /// /// 创建 /// /// XML节. /// XML读取器. public static XmlTextReader CreateReader( string fregment ) { XmlParserContext context = new XmlParserContext( null, null, null, XmlSpace.None ); context.Encoding = Encoding.GetEncoding( "gb2312" ); return new XmlTextReader( fregment, XmlNodeType.Element, context ); } /// /// 读取XML文件. /// /// XML文件名. /// 文件路径. /// 属性名. public static string Read( string xmlFile, string path, string attr ) { string cdFregment = XmlToolkit.ReadFregment( xmlFile, path ); XmlTextReader reader = XmlToolkit.CreateReader( cdFregment ); string _value = null; while( reader.Read() ) { if( reader.NodeType == XmlNodeType.Element && reader.Name == Path.GetFileName( path ) ) { _value = reader.GetAttribute( attr ); break; } } reader.Close(); return _value; } } //class XmlToolkit }

你可能感兴趣的:(XML工具类)