获取
获取node
通过doc对象执行SelectSingleNode或SelectNodes来发生
demo:[在根节点下获取子节点]
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlName);
XmlNode root = xmlDoc.DocumentElement;
XmlNodeList xmlNodelist = root.SelectNodes("xmlChildNode");
XmlNode xmlNode = root.SelectSingleNode("xmlChildNode");
string node_text = xmlNode.InnerText;
获取Attribute值
通过node对象获取Attributes集合来获取Attribute值
demo:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlName);
XmlNode node = xmlDoc.DocumentElement;
XmlAttribute attr = node.Attributes["Name"];
if(attr!=null)
string attr_value = attr.Value;
添加
添加node
通过doc对象执行CreateElement来发生
对任何层级节点的子节点添加都可通过父节点执行AppendChild来添加,注意,任何节点只能在拥有子节点与拥有节点值中二选一,即只拥有子节点或者只拥有InnerText,一旦执行node.InnerText,该节点的所有子节点将被去除;
demo:[在根节点下创建新的子节点]
XmlDocument xmlDoc = new XmlDocument();//创建xml文件对象
xmlDoc.Load(xmlName);//载入xml文件
XmlNode root = xmlDoc.DocumentElement;//获取文件的根节点
XmlNode new_node = xmlDoc.CreateElement(newNode);//在文件对象中创建一个新的节点
root.AppendChild(new_node);//将新建节点添加为root节点的子节点,即作为根节点的子节点
xmlDoc.Save(xmlName);//保存xml
添加或修改Attribute
通过doc对象执行CreateAttribute来发生
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlName);
XmlAttribute new_attribute = xmlDoc.CreateAttribute("Name");
new_attribute.Value = "Jack";
node.Attributes.SetNamedItem(new_attribute);
xmlDoc.Save(xmlName);
移除
移除node
通过node对象执行RemoveChild来发生
demo:[移除某子节点]
mlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlName);
XmlNode node = xmlDoc.DocumentElement;
XmlNode xmlNode = node.SelectSingleNode("xmlChildNode");
node.RemoveChild(xmlNode);
移除Attribute
通过node对象获取Attributes集合并通过Remove或RemoveAt或RemoveNamedItem来发生
demo:[移除某属性]
XmlDocument xmlDoc = new XmlDocument()
xmlDoc.Load(xmlName)
XmlNode node = xmlDoc.DocumentElement
XmlAttribute attr = node.Attributes["Name"]
node.Attributes.Remove(attr)
node.Attributes.RemoveAt(0)
node.Attributes.RemoveNamedItem("Name")