using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Xml;using System.Text;
namespace XMLStudy{ public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { StringBuilder sb=new StringBuilder(); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.Append("<orders xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"); sb.Append("<orderid>SO1231231</orderid>"); sb.Append("<sender>"); sb.Append("<Gender>female</Gender>"); sb.Append("</sender>"); sb.Append("</orders>"); Read(sb.ToString(), "orders", "xmlns:xsi"); }
public void WriteXML() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null)); //Create the root node and append into doc XmlElement el = xmlDoc.CreateElement("orders"); XmlAttribute attrID = xmlDoc.CreateAttribute("xmlns:xsi"); attrID.Value = "http://www.w3.org/2001/XMLSchema-instance"; el.Attributes.Append(attrID); xmlDoc.AppendChild(el); XmlElement elementContact = xmlDoc.CreateElement("orderid"); elementContact.InnerText = "SO1231231"; el.AppendChild(elementContact); // Contact Name XmlElement sender22 = xmlDoc.CreateElement("sender"); el.AppendChild(sender22); // Contact Gender XmlElement elementGender = xmlDoc.CreateElement("Gender"); elementGender.InnerText = "female"; sender22.AppendChild(elementGender); //xmlDoc.Save(Server.MapPath("Test.xml")); Response.Write(xmlDoc.InnerXml); }
/// <summary> /// 读取节点中某一个属性的值。如果attribute为空,则返回整个节点的InnerText,否则返回具体attribute的值 /// </summary> /// <param name="path">xml文件路径</param> /// <param name="node">节点</param> /// <param name="attribute">节点中的属性</param> /// <returns>如果attribute为空,则返回整个节点的InnerText,否则返回具体attribute的值</returns> /// 使用实例: XMLHelper.Read(path, "PersonF/person[@Name='Person2']", ""); /// XMLHelper.Read(path, "PersonF/person[@Name='Person2']", "Name"); public static string Read(string path, string node, string attribute) { string value = ""; try { XmlDocument doc = new XmlDocument(); doc.LoadXml(path); XmlNode xn = doc.SelectSingleNode(node); //xn=xn.SelectSingleNode(attribute); value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value); } catch (Exception e) { Console.WriteLine(e.Message); } return value; }
protected void Button1_Click(object sender, EventArgs e) { StringBuilder richTextBox1 = new StringBuilder(); richTextBox1.Clear(); XmlReader rdr = XmlReader.Create(Server.MapPath("Test.xml")); while (rdr.Read()) { if (rdr.NodeType == XmlNodeType.Text) {
richTextBox1.Append(rdr.Value + "\r\n"); } } TextBox1.Text = richTextBox1.ToString(); } }}
转载于:https://www.cnblogs.com/huijie/p/3610425.html