//1.將.xml文件讀入到string當中:
StreamReader sR = new StreamReader(Server.MapPath("XMLProcess.xml"),Encoding.UTF8);
string xXml = sR.ReadToEnd();
//2.dataset與xml及.xsd之間的轉換:
DataSet dsXml = new DataSet();
dsXml.ReadXml(Server.MapPath("XMLProcess.xml"));//讀取.xml到dataset里
dsXml.WriteXml(Server.MapPath("XMLProcess.xml"));//將dataset中的內容寫入.xml文件中
dsXml.ReadXmlSchema(Server.MapPath("XMLProcessSchema.xsd"));//讀取.xsd文件的表結構寫入dataset
dsXml.WriteXmlSchema(Server.MapPath("XMLProcessSchema.xsd"));//將dataset表的結構寫入.xsd文件
XmlDocument doc = new XmlDocument();
//doc.Load(Server.MapPath("XMLProcess.xml"));//讀取的第一種方式:通過文件路徑
//讀取的第二種方式:通過讀取string
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +"<title>Pride And Prejudice</title>" +"</book>");
XmlElement root = doc.DocumentElement;//獲取根結點元素
XmlAttributeCollection attributes = root.Attributes;//attribute即屬性:就是<book標籤下的genre和ISBN
// 改變<book的第二個屬性值
root.Attributes[1].Value = "fiction";
string strAttribute = attributes["ISBN"].Value;//獲取屬性名為"ISBN"的值
XmlDocument xdoc = new XmlDocument();
//xdoc.Load(Server.MapPath("XMLProcess.xml"));
xdoc.LoadXml(xXml);
XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(xdoc.NameTable);
//添加兩個xml命名空間,添加形式如下:<node xmlns="http://yu/liangjin" name="liangjin" title="測試">
namespaceMgr.AddNamespace("wf", "http://yu/liangjin");//wf,yu都是自定議的命名前綴,可以隨便定
namespaceMgr.AddNamespace("yu", "http://yuliangjin/yu");
XmlElement element = xdoc.DocumentElement;
XmlNode tmp = element.SelectSingleNode("wf:start", namespaceMgr);//選取符合XPath 運算式的第一個XmlNode
string ss = tmp.InnerText;//獲取該節點下的text的值
string ww = tmp.InnerXml;//獲取該節點下的xml的值
//遍歷該節點的所有屬性,取出屬性名為name的值
XmlElement startElement = (XmlElement)tmp;
foreach (XmlAttribute attribut in startElement.Attributes)
{
if (attribut.Name == "name")
{
myTest = attribut.InnerXml.Trim();
}
}
//取出所有名為node的節點
XmlNodeList tmpList = element.SelectNodes("wf:node", namespaceMgr);
int i = 1;
//遍歷所有的node節點,取出node節點屬性名為name的值
foreach (XmlNode singNode in tmpList)
{
startElement = (XmlElement)singNode;
if (singNode.Attributes["name"].Value == "")
{
Response.Write("為空哦!<br/>" + i.ToString());
}
else
{
Response.Write("值為:" + singNode.Attributes["name"].InnerText + i.ToString() + "<br/>");
}
i++;
}