xml 封裝與解析(javascript和C#中)

來源:互聯網
上載者:User

1.xml的解析(javascript中):
具體代碼如下,解析的結果root為Dom樹。 複製代碼 代碼如下:if (window.ActiveXObject){
var doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.loadXML(strXml);
}else{
var parser=new DOMParser();
var doc=parser.parseFromString(strXml,"text/xml");
}
var root = doc.documentElement;

2.xml的封裝(javascript中):
(該代碼為將頁面中table封裝為一個xml) 複製代碼 代碼如下:var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML("<Rows></Rows>");
var root = xmlDoc.documentElement;
for(var index=0;index<this.table.rows.length;index++)
{
var row = xmlDoc.createElement("Row");
for(var colIndex = 0;colIndex<this.table.rows[index].cells.length;colIndex++)
{
var currentCell = this.table.rows[index].cells[colIndex];
var cell = xmlDoc.createElement("Cell");
cell.setAttribute("Name",this.table.columns[colIndex].id);
cell.setAttribute("Value",currentCell.value);
row.appendChild(cell);
}
root.appendChild(row);
}

對於ajax實現前台xml到背景傳輸可以參考jquery實現xml的前後台傳輸。
3.xml的封裝:(C#)
具體方法如下, 複製代碼 代碼如下:XmlDocument doc = new XmlDocument();
doc.LoadXml("<Data></Data>");
XmlElement root = doc.DocumentElement;
root.SetAttribute("Name", name);//此處name為該xml賦一個Name屬性
foreach (ListObject Object in ListResult)//其中listResult為一個由listObject對象組成的list表,其中object為listResult的一個元素,他是ListObject型的
{
XmlElement item = doc.CreateElement("Item");
item.SetAttribute("Key", Object.key);//其中key,value分別為Object的屬性元素
item.SetAttribute("Value", Object.Value);
root.AppendChild(item);
}

最後產生的root即為xml.
4.xml的解析(c#) 複製代碼 代碼如下:XmlDocument doc = new XmlDocument();
try
{
doc.Load(Request.InputStream);//此處載入request請求的xml流
}
catch (Exception e)
{}
XmlNodeList rowList;
rowList = doc.DocumentElement.SelectNodes("Row");
List<ObjectVO> voList = new List<ObjectVO>(rowList.Count);//初始化一個List,改list中組成元素是ObjectVO對象
foreach (XmlNode row in rowList)
{
ObjectVO VO = new ObjectVO();
VO.VOElement1 = Convert.ToInt32((row.SelectSingleNode("Cell[@Name='VOElement1']") as XmlElement).GetAttribute("Value"));//vo中元素VOElement1為int型
VO.VOElement2 = (row.SelectSingleNode("Cell[@Name='VOElement2']") as XmlElement).GetAttribute("Value").ToString();//或取xml中cell元素中name為VOElement2的value屬性的值
VO.VOElement3 = (row.SelectSingleNode("Cell[@Name='VOElement3']") as XmlElement).GetAttribute("Value").ToString();
voList.Add(VO);
}
return voList;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.