XmlDocument to Byte[] and bytes[] to xmldocument or xdocument.

来源:互联网 发布:no sleep mac下载 编辑:程序博客网 时间:2024/06/11 07:44
一 、 XmlDocument to Byte[]
  //create xmldocument
XmlDocument xmlDoc = new XmlDocument();            //创建根节点            XmlElement root = xmlDoc.CreateElement("Books");            xmlDoc.AppendChild(root);            XmlNode book;            for (int i = 0; i < 10; i++)            {                book = xmlDoc.CreateElement("file");                book.InnerText = string.Concat("file", i.ToString());                root.AppendChild(book);            }
StringWriter sw = new StringWriter();XmlTextWriter xw = new XmlTextWriter(sw);                        // Save Xml Document to Text Writter.xmlDoc.WriteTo(xw);System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();                        // Convert Xml Document To Byte Array.byte[] docAsBytes = encoding.GetBytes(sw.ToString());
//from stream of xmldocument  ,out put element.
  Stream st = (Stream)xmlstream;
                XDocument xd = XDocument.Load(st);
                //var aa=from aa in xd.n                 var aa = from bb in xd.Descendants("file")                         select bb.Value;
                foreach (var item in aa)                {                    str += item.ToString();                }
二 byte[] to xmldocument  or XDocument
   byte[]stream =new byte[1000]
   .
   . 
   .  中间操作是把xmldocument 流写入到 stream 中 或是从别处传来的已有值的 byte[]。
   MemoryStream memoryStream=new MemoryStream(stream);
                XmlReader xmlreader = new XmlTextReader(memoryStream);                XmlDocument xmldocumet = new XmlDocument();                xmldocumet.Load(xmlreader); (或                 XDocument xd = new XDocument();
                xd.load(xmlreader)
        )
原创粉丝点击