/// <summary>
/// Author: jiangxiaoqiang
/// </summary>
public
class
XmlReader
{
//========================================================= //
#region 获取XmlDocument对象
/// <summary>
/// </summary>
/// <param name="xmlFileContent"></param>
/// <returns></returns>
public
static
XmlDocument GetXmlDocByXmlContent(
string
xmlFileContent)
{
if
(
string
.IsNullOrEmpty(xmlFileContent))
{
return
null
;
}
var xDoc =
new
XmlDocument();
try
{
xDoc.LoadXml(xmlFileContent);
}
catch
{
xDoc =
null
;
}
return
xDoc;
}
/// <summary>
/// </summary>
/// <param name="xmlFilePath"></param>
/// <returns></returns>
public
static
XmlDocument GetXmlDocByFilePath(
string
xmlFilePath)
{
if
(
string
.IsNullOrEmpty(xmlFilePath) || !File.Exists(xmlFilePath))
{
return
null
;
}
var xDoc =
new
XmlDocument();
try
{
xDoc.Load(xmlFilePath);
}
catch
{
}
return
xDoc;
}
#endregion
//========================================================= //
//========================================================= //
#region 获取XML节点(或节点列表)
/// <summary>
/// </summary>
/// <param name="parentXmlNode"></param>
/// <param name="childNodeName"></param>
/// <returns></returns>
public
static
XmlNode GetFirstChildNodeByName(XmlNode parentXmlNode,
string
childNodeName)
{
var childXmlNodes = GetChildNodesByName(parentXmlNode,childNodeName);
if
(childXmlNodes !=
null
&& childXmlNodes.Count > 0)
{
return
childXmlNodes[0];
}
return
null
;
}
/// <summary>
/// </summary>
/// <param name="parentXmlNode">父节点</param>
/// <param name="nodeName">节点名称</param>
/// <returns></returns>
public
static
XmlNodeList GetChildNodesByName(XmlNode parentXmlNode,
string
nodeName)
{
if
(parentXmlNode ==
null
||
string
.IsNullOrEmpty(nodeName))
{
return
null
;
}
return
GetChildNodesByXPathExpr(parentXmlNode,
string
.Format(
".//{0}"
,nodeName));
}
/// <summary>
/// 获取父节点下满足xpathExpr表达式的XML子节点列表
/// </summary>
/// <param name="parentXmlNode">父节点</param>
/// <param name="xpathExpr"></param>
/// <returns></returns>
public
static
XmlNodeList GetChildNodesByXPathExpr(XmlNode parentXmlNode,
string
xpathExpr)
{
if
(parentXmlNode ==
null
||
string
.IsNullOrEmpty(xpathExpr))
{
return
null
;
}
return
parentXmlNode.SelectNodes(xpathExpr);
}
/// <summary>
/// 获取父节点下的第一个子节点
/// </summary>
/// <param name="parentXmlNode"></param>
/// <returns></returns>
public
static
XmlNode GetFirstChildNode(XmlNode parentXmlNode)
{
var childXmlNodes = GetChildNodes(parentXmlNode);
if
(childXmlNodes !=
null
&& childXmlNodes.Count > 0)
{
return
childXmlNodes[0];
}
return
null
;
}
/// <summary>
/// 获取父节点的子节点列表
/// </summary>
/// <param name="parentXmlNode">父节点</param>
/// <returns></returns>