using System; using System.Linq; using System.Xml; /// <summary> /// XmlNodeHelper /// </summary> public static class XmlNodeHelper { /// <summary> /// 获取给定XmlNode所在的Document /// </summary> /// <param name="parentNode">给定XmlNode</param> /// <returns>XmlDocument</returns> public static XmlDocument GetDocument(this XmlNode parentNode) { if (parentNode == null) { throw new Exception("XmlNode不能为空"); } var document = (parentNode as XmlDocument) ?? parentNode.OwnerDocument; if (document == null) { throw new Exception("XmlDocument不能为空"); } return document; } /// <summary> /// 为给定结点创建子结点 /// </summary> /// <param name="parentNode">给定结点</param> /// <param name="name">子结点名称</param> /// <returns>子结点</returns> public static XmlNode CreateChildNode(this XmlNode parentNode, string name) { var document = parentNode.GetDocument(); var node = document.CreateElement(name); parentNode.AppendChild(node); return node; } /// <summary> /// 为给定结点创建子结点 /// </summary> /// <param name="parentNode">给定结点</param> /// <param name="name">子结点名称</param> /// <param name="namespaceUri">子结点命名空间</param> /// <returns>子结点</returns> public static XmlNode CreateChildNode(this XmlNode parentNode, string name, string namespaceUri) { var document = parentNode.GetDocument(); var node = document.CreateElement(name, namespaceUri); parentNode.AppendChild(node); return node; } /// <summary> /// 根据属性名称获取给定结点的属性值 /// </summary> /// <param name="node">给定结点</param> /// <param name="attributeName">属性名称</param> /// <returns>属性值</returns> public static string GetAttribute(this XmlNode node, string attributeName) { return node.GetAttribute(attributeName, null); } /// <summary> /// 根据属性名称获取给定结点的属性值 /// </summary> /// <param name="node">给定结点</param> /// <param name="attributeName">属性名称</param> /// <param name="defaultValue">默认值</param> /// <returns>属性值</returns> public static string GetAttribute(this XmlNode node, string attributeName, string defaultValue) { if (node.Attributes == null) { return null; } var attribute = node.Attributes[attributeName]; return (attribute != null ? attribute.InnerText : defaultValue); } /// <summary> /// 为给定结点设置属性名称与值(如果不存在属性名称,则新增;否则更改) /// </summary> /// <param name="node">给定结点</param> /// <param name="name">属性名称</param> /// <param name="value">属性值</param> public static void SetAttribute(this XmlNode node, string name, string value) { if (node == null || node.Attributes == null) { return; } var nodeAttributes = node.Attributes; var attribute = nodeAttributes[name, node.NamespaceURI]; if (attribute == null) { var document = node.GetDocument(); attribute = document.CreateAttribute(name, document.NamespaceURI); nodeAttributes.Append(attribute); } attribute.InnerText = value; } }