初始时,偶滴webservice只是返回一个string的,后来经理要求返回值为xml类型的数据
查了一下,如果dataset什么的貌似还得序列化,xml就不用了,直接声明拼好之后return就ok了
只是我要返回的xml是动态的,需要依据每次用户输入的action type数量来循环拼接返回的xml,搞的代码长的要命 = =
具体代码:
先导入命名空间 using System.Xml;
XmlDocument创建XML文档
XmlDocument xmlDoc = new XmlDocument();
// 建立Xml的定义声明
XmlDeclaration dec = xmlDoc.CreateXmlDeclaration( " 1.0 " , " GB2312 " , null );
xmlDoc.AppendChild(dec);
// 创建根节点
XmlElement root = xmlDoc.CreateElement( " Books " );
xmlDoc.AppendChild(root);
XmlNode book = xmlDoc.CreateElement( " Book " );
XmlElement title = xmlDoc.CreateElement( " Title " );
title.InnerText = " SQL Server " ;
book.AppendChild(title);
XmlElement isbn = xmlDoc.CreateElement( " ISBN " );
isbn.InnerText = " 444444 " ;
book.AppendChild(isbn);
XmlElement author = xmlDoc.CreateElement( " Author " );
author.InnerText = " jia " ;
book.AppendChild(author);
XmlElement price = xmlDoc.CreateElement( " Price " );
price.InnerText = " 120 " ;
price.SetAttribute( " Unit " , " ___FCKpd___0quot;);
book.AppendChild(price);
root.AppendChild(book);
xmlDoc.Save( " Books.xml " );
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( " Books.xml " );
XmlNode root = xmlDoc.SelectSingleNode( " Books " );
XmlElement book = xmlDoc.CreateElement( " Book " );
XmlElement title = xmlDoc.CreateElement( " Title " );
title.InnerText = " XML " ;
book.AppendChild(title);
XmlElement isbn = xmlDoc.CreateElement( " ISBN " );
isbn.InnerText = " 333333 " ;
book.AppendChild(isbn);
XmlElement author = xmlDoc.CreateElement( " Author " );
author.InnerText = " snow " ;
book.AppendChild(author);
XmlElement price = xmlDoc.CreateElement( " Price " );
price.InnerText = " 120 " ;
price.SetAttribute( " Unit " , " ___FCKpd___0quot;);
book.AppendChild(price);
root.AppendChild(book);
xmlDoc.Save( " Books.xml " );
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( " Books.xml " );
// " // Book[@Unit="$"]"
// 获取Books节点的所有子节点
XmlNodeList nodeList = xmlDoc.SelectSingleNode( " Books//Book " ).ChildNodes;
// 遍历所有子节点
foreach (XmlNode xn in nodeList)
{
// 将子节点类型转换为XmlElement类型
XmlElement xe = (XmlElement)xn;
if (xe.Name == " Author " )
{
xe.InnerText = " amandag " ;
}
if (xe.GetAttribute( " Unit " ) == " ___FCKpd___0quot;)
{
xe.SetAttribute( " Unit " , " ¥ " );
}
}
xmlDoc.Save( " Books.xml " );
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( " Books.xml " );
XmlNodeList nodeList = xmlDoc.SelectSingleNode( " Books//Book " ).ChildNodes;
// 遍历所有子节点
foreach (XmlNode xn in nodeList)
{
// 将子节点类型转换为XmlElement类型
XmlElement xe = (XmlElement)xn;
if (xe.Name == " Author " )
{
xe.RemoveAll();
}
if (xe.GetAttribute( " Unit " ) == " ¥ " )
{
xe.RemoveAttribute( " Unit " );
}
}
xmlDoc.Save( " Books.xml " );
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace XMLDOMDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLoad_Click( object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( " Books.xml " );
MessageBox.Show(xmlDoc.InnerXml);
}
// 创建文档
private void btnCreate_Click( object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
// 建立Xml的定义声明
XmlDeclaration dec = xmlDoc.CreateXmlDeclaration( " 1.0 " , " GB2312 " , null );
xmlDoc.AppendChild(dec);
// 创建根节点
XmlElement root = xmlDoc.CreateElement( " Books " );
xmlDoc.AppendChild(root);
XmlNode book = xmlDoc.CreateElement( " Book " );
XmlElement title = xmlDoc.CreateElement( " Title " );
title.InnerText = " SQL Server " ;
book.AppendChild(title);
XmlElement isbn = xmlDoc.CreateElement( " ISBN " );
isbn.InnerText = " 444444 " ;
book.AppendChild(isbn);
XmlElement author = xmlDoc.CreateElement( " Author " );
author.InnerText = " jia " ;
book.AppendChild(author);
XmlElement price = xmlDoc.CreateElement( " Price " );
price.InnerText = " 120 " ;
price.SetAttribute( " Unit " , " ___FCKpd___0quot;);
book.AppendChild(price);
root.AppendChild(book);
xmlDoc.Save( " Books.xml " );
}
private void btnInsert_Click( object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( " Books.xml " );
XmlNode root = xmlDoc.SelectSingleNode( " Books " );
XmlElement book = xmlDoc.CreateElement( " Book " );
XmlElement title = xmlDoc.CreateElement( " Title " );
title.InnerText = " XML " ;
book.AppendChild(title);
XmlElement isbn = xmlDoc.CreateElement( " ISBN " );
isbn.InnerText = " 333333 " ;
book.AppendChild(isbn);
XmlElement author = xmlDoc.CreateElement( " Author " );
author.InnerText = " snow " ;
book.AppendChild(author);
XmlElement price = xmlDoc.CreateElement( " Price " );
price.InnerText = " 120 " ;
price.SetAttribute( " Unit " , " ___FCKpd___0quot;);
book.AppendChild(price);
root.AppendChild(book);
xmlDoc.Save( " Books.xml " );
MessageBox.Show( " 数据已写入! " );
}
private void btnUpdate_Click( object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( " Books.xml " );
// " // Book[@Unit=\"$\"]"
// 获取Books节点的所有子节点
XmlNodeList nodeList = xmlDoc.SelectSingleNode( " Books//Book " ).ChildNodes;
// 遍历所有子节点
foreach (XmlNode xn in nodeList)
{
// 将子节点类型转换为XmlElement类型
XmlElement xe = (XmlElement)xn;
if (xe.Name == " Author " )
{
xe.InnerText = " amandag " ;
}
if (xe.GetAttribute( " Unit " ) == " ___FCKpd___0quot;)
{
xe.SetAttribute( " Unit " , " ¥ " );
}
// break;
}
// XmlNodeList nodeList = xmlDoc.SelectNodes("Books // Book");
// foreach (XmlNode xn in nodeList)
// {
// foreach (XmlNode x in xn.ChildNodes)
// {
// // 将子节点类型转换为XmlElement类型
// XmlElement xe = (XmlElement)x;
// if (xe.Name == "Author")
// {
// xe.InnerText = "amandag";
// }
// if (xe.GetAttribute("Unit") == "___FCKpd___0quot;)
// {
// xe.SetAttribute("Unit", "¥");
// }
// // break;
// }
// }
xmlDoc.Save( " Books.xml " );
}
private void btnDelete_Click( object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( " Books.xml " );
XmlNodeList nodeList = xmlDoc.SelectSingleNode( " Books//Book " ).ChildNodes;
// 遍历所有子节点
foreach (XmlNode xn in nodeList)
{
// 将子节点类型转换为XmlElement类型
XmlElement xe = (XmlElement)xn;
if (xe.Name == " Author " )
{
xe.RemoveAll();
}
if (xe.GetAttribute( " Unit " ) == " ¥ " )
{
xe.RemoveAttribute( " Unit " );
}
}
xmlDoc.Save( " Books.xml " );
}
}
}
From:http://blog.csdn.net/amandag/archive/2008/07/08/2623322.aspx
XmlDocument是表示DOM的类。
1.加载XML文档:使用load()方法加载XML文档;
2.读取节点:使用GetElementById()、GetElementsByTagName()方法根据ID或标签名读取节点;
3.查找节点:使用SelectSingleNode(string search)方法通过XPath查找节点;
4.插入节点:使用CreateElement()方法创建节点,AppendChild()方法添加新节点;
5.创建文档:通过XmlDeclaration对象新建声明节点,其他同插入节点。
using System;
using System.Xml;
namespace Magci.Test.XML.TestXmlDocment
{
class Program
{
private static XmlDocument doc;
static void Main( string [] args)
{
doc = new XmlDocument();
// 加载XML文档
doc.Load( @" ..\..\books.xml " );
DisplayTitle();
SearchByTitle( " The Gorgias " );
Insert();
CreateDoc();
Console.ReadLine();
}
// 遍历节点
public static void DisplayTitle()
{
XmlNodeList nodes = doc.GetElementsByTagName( " title " );
Console.WriteLine( " Title: " );
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.InnerText);
}
}
// 根据title查找
public static void SearchByTitle( string title)
{
string search = " bookstore/book[title=' " + title + " '] " ;
XmlNode foundNode = doc.SelectSingleNode(search);
Console.WriteLine( " \nSearch by title: " );
if (foundNode != null )
{
Console.WriteLine(foundNode.InnerText);
}
else
{
Console.WriteLine( " Not Found! " );
}
}
// 插入节点
public static void Insert()
{
// 创建book元素
XmlElement newBook = doc.CreateElement( " book " );
newBook.SetAttribute( " genre " , " MyStery " );
newBook.SetAttribute( " publicationdate " , " 2001 " );
newBook.SetAttribute( " ISBN " , " 123456789 " );
// 创建title元素
XmlElement newTitle = doc.CreateElement( " title " );
newTitle.InnerText = " The Case of the Missing Cookie " ;
// 将title元素添加到book元素中
newBook.AppendChild(newTitle);
XmlElement newAuthor = doc.CreateElement( " author " );
newBook.AppendChild(newAuthor);
XmlElement newName = doc.CreateElement( " name " );
newName.InnerText = " C.Monster " ;
newAuthor.AppendChild(newName);
XmlElement newPrice = doc.CreateElement( " price " );
newPrice.InnerText = " 9.99 " ;
newBook.AppendChild(newPrice);
// 将新建的book元素加入到XML文档中
doc.DocumentElement.AppendChild(newBook);
// 另存为
XmlTextWriter tr = new XmlTextWriter( @" ..\..\booksEdit.xml " , null );
tr.Formatting = Formatting.Indented;
doc.WriteContentTo(tr);
tr.Close();
Console.WriteLine( " \nbooksEdit.xml Saved successful.\n " );
XmlNodeList nodes = doc.GetElementsByTagName( " title " );
Console.WriteLine( " Display title after Insert: " );
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.InnerText);
}
}
// 创建文档
public static void CreateDoc()
{
XmlDocument newDoc = new XmlDocument();
// 创建声明节点
XmlDeclaration newDec = newDoc.CreateXmlDeclaration( " 1.0 " , " utf-8 " , null );
newDoc.AppendChild(newDec);
XmlElement newRoot = newDoc.CreateElement( " bookstore " );
newDoc.AppendChild(newRoot);
XmlElement newBook = newDoc.CreateElement( " book " );
newBook.SetAttribute( " genre " , " MyStery " );
newBook.SetAttribute( " publicationdate " , " 2001 " );
newBook.SetAttribute( " ISBN " , " 123456789 " );
XmlElement newTitle = newDoc.CreateElement( " title " );
newTitle.InnerText = " The Case of the Missing Cookie " ;
newBook.AppendChild(newTitle);
XmlElement newAuthor = newDoc.CreateElement( " author " );
newBook.AppendChild(newAuthor);
XmlElement newName = newDoc.CreateElement( " name " );
newName.InnerText = " C.Monster " ;
newAuthor.AppendChild(newName);
XmlElement newPrice = newDoc.CreateElement( " price " );
newPrice.InnerText = " 9.99 " ;
newBook.AppendChild(newPrice);
newRoot.AppendChild(newBook);
XmlTextWriter tr = new XmlTextWriter( @" ..\..\booksCreate.xml " , null );
tr.Formatting = Formatting.Indented;
newDoc.WriteContentTo(tr);
tr.Close();
Console.WriteLine( " \nbooksCreate.xml Saved successful.\n " );
XmlNodeList nodes = newDoc.GetElementsByTagName( " title " );
Console.WriteLine( " Display title after Create: " );
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.InnerText);
}
}
}
}
// books.xml:
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< bookstore >
< book genre = " autobiography " publicationdate = " 1991 " ISBN = " 1-861003-11-0 " >
< title > The Autobiography of Benjamin Franklin </ title >
< author >
< first - name > Benjamin </ first - name >
< last - name > Franklin </ last - name >
</ author >
< price > 8.99 </ price >
</ book >
< book genre = " novel " publicationdate = " 1967 " ISBN = " 0-201-63361-2 " >
< title > The Confidence Man </ title >
< author >
< first - name > Herman </ first - name >
< last - name > Melville </ last - name >
</ author >
< price > 11.99 </ price >
</ book >
< book genre = " philosophy " publicationdate = " 1991 " ISBN = " 1-861001-57-6 " >
< title > The Gorgias </ title >
< author >
< name > Plato </ name >
</ author >
< price > 9.99 </ price >
</ book >
</ bookstore >
// booksEdit.xml:修改后的XML文档
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< bookstore >
< book genre = " autobiography " publicationdate = " 1991 " ISBN = " 1-861003-11-0 " >
< title > The Autobiography of Benjamin Franklin </ title >
< author >
< first - name > Benjamin </ first - name >
< last - name > Franklin </ last - name >
</ author >
< price > 8.99 </ price >
</ book >
< book genre = " novel " publicationdate = " 1967 " ISBN = " 0-201-63361-2 " >
< title > The Confidence Man </ title >
< author >
< first - name > Herman </ first - name >
< last - name > Melville </ last - name >
</ author >
< price > 11.99 </ price >
</ book >
< book genre = " philosophy " publicationdate = " 1991 " ISBN = " 1-861001-57-6 " >
< title > The Gorgias </ title >
< author >
< name > Plato </ name >
</ author >
< price > 9.99 </ price >
</ book >
< book genre = " MyStery " publicationdate = " 2001 " ISBN = " 123456789 " >
< title > The Case of the Missing Cookie </ title >
< author >
< name > C.Monster </ name >
</ author >
< price > 9.99 </ price >
</ book >
</ bookstore >
// booksCreate.xml:新建的XML文档
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< bookstore >
< book genre = " MyStery " publicationdate = " 2001 " ISBN = " 123456789 " >
< title > The Case of the Missing Cookie </ title >
< author >
< name > C.Monster </ name >
</ author >
< price > 9.99 </ price >
</ book >
</ bookstore >
用MessageBox要先导入命名空间: using System.Windows.Forms;
MessageBox.Show("数据已写入!");
Error: This document already has a 'DocumentElement' node
1. Please check if you have used method AppendChild() under document. If this is the case you will need to do it for "document.DocumentElement" instead of just docuemnt.
其实我想不通是为什么,难道根节点下只能有一个总的结点???
<?xml >
<aa></aa>
<bb></bb>
报错
改为这样就没问题了.... orz
<?xml >
<value>
<aa></aa>
<bb></bb>
</value>
另外,因为具体action的操作是for循环逐个去执行的,为了得到每个返回的信息把生成xml结点的语句放在每个action后面
本来为了少点代码,统一在前面声明的共同结点,各个子节点里只要赋值就好了,然后append到上级结点。可是后来发现,这么操作最后xml里只剩下最后一次action操作的结果,前面的结点都被覆盖了.... 后改为每个action type中各自重新声明结点后一切正常了....
为啥米捏?同一个对象没清空?
其他生成xml的方法参考资料——
如果规律的话,用dataset也不错 DataSet.GetXml()
http://hi.baidu.com/lostsolar/blog/item/dcfe8a5561bed85fd00906b2.html
WebService :实现DataSet , DataTable , XML 的返回...
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Xml;
/// <summary>
/// AdminService 的摘要说明
/// </summary>
[WebService(Namespace = " http://tempuri.org/ " )]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
/* 管理远程服务接口
* 创建人:
* 创建日期:09-07-16
* 修改人:
* 修改日期:
* 在WebService的方法中为DataTable命名,否则引用端会报错!
*/
[Serializable]
public class AdminService : System.Web.Services.WebService
{
public AdminService()
{
// 如果使用设计的组件,请取消注释以下行
// InitializeComponent();
}
[WebMethod(Description = " DataSet集合 " )]
public DataSet GetDataSet()
{
DataTable dt = new DataTable( " mytable " );
DataColumn dc = new DataColumn( " id " , typeof ( string ));
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr[ " id " ] = " 1111111 " ;
dt.Rows.Add(dr);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
[WebMethod(Description = " dt帐号集合 " )]
public DataTable getAccounts(String ID)
{
// = new DataTable("Accounts")
DataTable dt = new DataTable();
dt.TableName = " Accounts " ;
dt.Columns.Add( " id " );
dt.Columns.Add( " name " );
for ( int i = 0 ; i < 10 ; i ++ )
{
DataRow dr = dt.NewRow();
dr[ " id " ] = i.ToString();
dr[ " name " ] = " name " + i.ToString();
dt.Rows.Add(dr);
}
return dt;
}
[WebMethod(Description = " xml " )]
public string xmlStr()
{
string str;
str = " <?xml version=\ " 1.0 \ " encoding=\ " utf - 8 \ " ?> " ;
str += " <Items> " ;
for ( int i = 1 ; i < 10 ; i ++ )
{
str += " <Item> " ;
str += " <name>nam " + i + " </name> " ;
str += " <grender>boy " + i + " </grender> " ;
str += " <from>shanghai " + i + " </from> " ;
str += " </Item> " ;
}
str += " </Items> " ;
XmlDocument dcxml = new XmlDocument();
dcxml.LoadXml(str);
return str;
}
}
http://www.cnblogs.com/Fooo/archive/2009/07/16/1524698.html
http://topic.csdn.net/u/20070207/11/a076f040-49d4-4b0f-a02c-3b673168b92d.html
http://www.cnblogs.com/RevengeBoy/archive/2007/07/03/803878.html
对webservice返回的XML文档的改进...反正就是要把减号去掉....
http://blog.csdn.net/xiao_jun_0820/archive/2007/08/09/1733629.aspx