将xml解析成一个类,方便查询使用。
类:
public class XMLObject : BaseGuid
{
public string NodeName { get; set; }
public Dictionary<string, string> Attributes { get; set; }
public string FartherName { get; set; }
public string FartherID { get; set; }
public List<XMLObject> Childs
{
get
{
return _childs;
}
set
{
_childs = value;
}
}
private List<XMLObject> _childs = new List<XMLObject>();
public static XMLObject GetXmlObj(XmlDocument doc, XmlElement farther, XMLObject xmlobj = null, XMLObject fartherObj = null)
{
XmlElement el;
if (xmlobj == null)
{
el = doc.DocumentElement;
xmlobj = new XMLObject();
xmlobj.NodeName = el.Name;
xmlobj.Attributes = getElAttri(el);
}
else
{
el = farther;
}
foreach (XmlNode node in el.ChildNodes)
{
if (node.NodeType != XmlNodeType.Comment)
{
XMLObject obj = new XMLObject();
obj.FartherName = el.Name;
obj.NodeName = node.Name;
obj.Attributes = getElAttri(node as XmlElement);
if (fartherObj != null)
{
obj.FartherID = fartherObj.ID;
fartherObj.Childs.Add(obj);
}
else
{
obj.FartherID = xmlobj.ID;
xmlobj.Childs.Add(obj);
}
if (node.ChildNodes.Count > 0)
{
GetXmlObj(doc, node as XmlElement, xmlobj, obj);
}
}
}
return xmlobj;
}
private static Dictionary<string, string> getElAttri(XmlElement el)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (XmlAttribute attr in el.Attributes)
{
dic.Add(attr.Name, attr.Value);
}
return dic;
}
}
tomcat配置文件conf.xml解析示例:
public List<WebSite> ListSite()
{
string conf = _tomcatDir + "\\conf\\server.xml";
if (!File.Exists(conf))
{
throw new Exception(string.Format("未找到tomcat的配置文件:{0}", conf));
}
XmlDocument doc = new XmlDocument();
doc.Load(conf);
XmlElement root = doc.DocumentElement;
XMLObject xmlobj = XMLObject.GetXmlObj(doc, root);
List<XMLObject> listWeb = xmlobj.Childs.Where(f => f.NodeName.ToLower() == "service").ToList();
List<WebSite> list = new List<WebSite>();
foreach (var obj in listWeb)
{
WebSite site = new WebSite();
site.SiteName = obj.Attributes.FirstOrDefault(f => f.Key.ToLower() == "name").Value;
var connector = obj.Childs.SingleOrDefault(f => f.NodeName.ToLower() == "connector" && f.Attributes["protocol"].ToLower().Contains("http"));
var engine = obj.Childs.SingleOrDefault(f => f.NodeName.ToLower() == "engine");
var host = engine.Childs.Where(f => f.NodeName.ToLower() == "host");
foreach (var v in host)
{
WebSite.Bind bind = new WebSite.Bind();
bind.Port = int.Parse(connector.Attributes.FirstOrDefault(f => f.Key.ToLower() == "port").Value);
bind.Host = v.Attributes.FirstOrDefault(f => f.Key.ToLower() == "name").Value; ;
site.BindList.Add(bind);
var context = v.Childs.SingleOrDefault(f => f.NodeName.ToLower() == "context");
if (context != null)
{
site.PhysicalPath = context.Attributes.FirstOrDefault(f => f.Key.ToLower() == "docbase").Value;
}
}
list.Add(site);
}
return list;
}