C# 对xml进行操作
一:xml的基本操作
(1)获得xml文件中的数据
//创建xml文档对象 XmlDocument xmlDoc = new XmlDocument(); //将指定xml文件加载xml文档对象上
xmlDoc.Load("D:/Documents/Visual Studio 2013/Projects/ReadXMLFile/ReadXMLFile/Customers.xml"); //表示文档中的单个节点
XmlNode node; //选择匹配 参数XPath 表达式的第一个 XmlNode。
node = xmlDoc.SelectSingleNode("config/username"); //获取或设置节点及其所有子节点的串联值。
string username = node.InnerText;
node = xmlDoc.SelectSingleNode("config/password");
string password = node.InnerText;
(2)将数据按照对应的字节逐个保存到另一个xml文件中
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNode node;
node = xmlDoc.SelectSingleNode("config/username");
if (node == null)
{
//创建节点
XmlElement n = xmlDoc.CreateElement("username");
//对节点属性值进行赋值
n.InnerText = username;
//将所创节点添加到已有节点后面
xmlDoc.SelectSingleNode("config").AppendChild(n);
}
else
{
node.InnerText = username;
}
node = xmlDoc.SelectSingleNode("config/password");
if (node == null)
{
XmlElement n = xmlDoc.CreateElement("password");
n.InnerText = password;
xmlDoc.SelectSingleNode("config").AppendChild(n);
}
else
{
node.InnerText = password;
}
//将xml文档对象保存到指定的xml文件中
xmlDoc.Save(Xpath);
(3)将包含xml的字符串保存为一个xml文件
StreamReader str = new StreamReader("D:/Documents/Visual Studio 2013/Projects/ReadXMLFile/ReadXMLFile/Customers.xml");
string readerXML = str.ReadToEnd();
str.Close();
此三句代码只是为了得到一个包含xml的字符串
//创建一个xml文档
XmlDocument xDoc = new XmlDocument();
//将指定字符串加载到xml文档对象中
xDoc.LoadXml(readerXML);
//将xml文档对象保存到指定文件中(若此文件不存在会自行创建)
xDoc.Save("D:/Documents/Visual Studio 2013/Projects/ReadXMLFile/ReadXMLFile/Response1.xml");
二:下面是之前写的一个项目中的一段代码,其功能是将xml文档转换成不带标签的有效对象。
C#内部封装的类库"namespace System.Net.Http class HttpClient",
(1)此内部有进行请求所用的方法此处用得时Post的异步请求,此时的请求头是固定的先忽略:
public class Post
{
private static readonly HttpClient _httpClient; //创建类库成员变量,以注入的方式进行方法调用
public async Task<string> PostAsync(string fileName, string url = "https://webservices3.sabre.com")
{
string result = string.Empty;
try
{
StreamReader sr = new StreamReader(fileName, Encoding.UTF8); //以一种特定的编码用字节流读取指定文件
string postContent = sr.ReadToEnd(); //从当前位置到末尾读取全部字节
sr.Close(); //关闭流
StringContent httpContent = new StringContent(postContent, Encoding.UTF8, "text/xml"); //基于字符串创建HTTP新实例,即将数据内容以特定编码写成特定格式的字符串新实例
var response = await _httpClient.PostAsync(url, httpContent); //以异步操作将 POST 请求发送给指定 URI,返回异步操作的任务对象(此对象形式根据请求文档规定可得到,此处为xml)
result = await response.Content.ReadAsStringAsync(); //获取HTTP响应消息内容并将内容写入异步流进行读取,得到包含xml的字符串(其存在节点,拥有xml文档的一切特性)
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
}
小结:首先要搞清楚如果对方接口接受请求的数据包是xml形式的,即使它是文档,也可以看做是有一种特定格式字符串。首先是直接将请求信息写成xml文件,然后用流读取此文件内容,使其转换成包含xml的字符串
(若对方要求将数据进行压缩也只是提高传输速度)
(2)对于此返回数据可以利用节点的读取进行有效数据的提取:
1:此xml中包含哪些命名空间要得到
2:从包含xml的字符串中得到根结点
3:利用Linq语法对此xml类型的字符串进行提取有效信息,并将这些数据赋给所需对象的实例
public class Connect
{
private string xmlFilePath = @"F:\API\NewSabreApi\Sabre.Api\TestWinForm\Xml\"; //此Xml文件夹下有好多xml文件
public void getData()
{
Post post=new Post();
var response=post.PostAsync(xmlFilePath + "BargainFinderMaxRs.xml");
//命名空间
XNamespace xsi = "http://www.opentravel.org/OTA/2003/05";
XNamespace soap_env = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace eb = "http://www.ebxml.org/namespaces/messageHeader";
XNamespace wsse = "http://schemas.xmlsoap.org/ws/2002/12/secext";
try
{
//从包含xml的字符串中得到根结点
XElement root = XElement.Parse(response);
#region
//根据节点提取数据并得到所要对象,此对象有可能是个对象集合,若要得到单个Segments对象需要对其进行遍历
var flightSegments = from flight in root.Elements(soap_env + "Body").Elements(xsi + "OTA_AirLowFareSearchRS")
.Elements(xsi + "PricedItineraries")
.Elements(xsi + "PricedItinerary")
select new Segments
{
carrier = flight.Element(xsi + "OperatingAirline").Attribute("Code").IsNamespaceDeclaration ? null :
(string)flight.Element(xsi +"OperatingAirline").Attribute("Code").Value,
depAirport = (string)flight.Element(xsi + "DepartureAirport").Attribute("LocationCode") == null ? null :
(string)flight.Element(xsi + "DepartureAirport").Attribute("LocationCode"),
depTime = DateTime.Parse(flight.Attribute("DepartureDateTime") == null ? null :
flight.Attribute("DepartureDateTime").Value).ToString("yyyyMMddHHmm"),
}
foreach(var flight in flightSegments)
{
//此处便可得到Segments类型的单个对象实例
//此时便可对此对象实例flight进行业务需求的操作
}
}
catch (Exception ex)
{
tbResult.Text = ex.Message;
}
}
}
C# 对xml进行操作的更多相关文章
- VS2012 Unit Test —— 我对IdleTest库动的大手术以及对Xml相关操作进行测试的方式
[1]我的IdleTest源码地址:http://idletest.codeplex.com/ [2]IdleTest改动说明:2013年10月份在保持原有功能的情况下对其动了较大的手术,首先将基本的 ...
- sql server中对xml进行操作
一.前言 SQL Server 2005 引入了一种称为 XML 的本机数据类型.用户可以创建这样的表,它在关系列之外还有一个或多个 XML 类型的列:此外,还允许带有变量和参数.为了更好地支持 XM ...
- 对XML的操作
对XML的操作主要使用到的语法示例: using System.Xml; private static string XmlMarketingStaff = AppDomain.CurrentDoma ...
- Xml通用操作类
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml ...
- C# XML流操作简单实例
这里我们先介绍操作XML文件的两个对象:XmlTextReader和XmlTextWriter打开和读取Xml文件使用到的对象就是XmlTextReader对象.下面的例子打开了与程序在同一路径下的一 ...
- SQL Server 2008 对XML 数据类型操作
原文 http://www.cnblogs.com/qinjian123/p/3240702.html 一.前言 从 SQL Server 2005 开始,就增加了 xml 字段类型,也就是说可以直接 ...
- 我来讲讲在c#中怎么进行xml文件操作吧,主要是讲解增删改查!
我把我写的四种方法代码贴上来吧,照着写没啥问题. 注: <bookstore> <book> <Id>1</Id> <tate>2010-1 ...
- 由“Jasperrpeorts 4.1.2升级到5.1.2对flex项目的解析”到AS3 带命名空间的XML的操作
原文同步至:http://www.waylau.com/from-jasperrpeorts-4-1-2-upgraded-to-5-1-2-parsing-of-flex-projects-to-t ...
- xml常用操作(js、sql、vb)
我们经常会用到xml操作,如下介绍了js.sql.vb等对xml的操作. JS创建xml对象 //创建对象 function getDataXML() { var objTds = $(&qu ...
- Python实现XML的操作
本文从以下两个方面, 用Python实现XML的操作: 一. minidom写入XML示例1 二. minidom写入XML示例2 三. ElementTree写入/修改示例 四. ElementTr ...
随机推荐
- 进程控制fork与vfork
1. 进程标识符 在前面进程描述一章节里已经介绍过进程的两个基本标识符pid和ppid,现在将详细介绍进程的其他标识符. 每个进程都有非负的整形表示唯一的进程ID.一个进程终止后,其进程ID就可以再次 ...
- angularjs应用prerender.io 搜索引擎优化实践
上一篇博文(http://www.cnblogs.com/ideal-lx/p/5625428.html)介绍了单页面搜索引擎优化的原理,以及介绍了两个开源框架的优劣.prerender框架的工作原理 ...
- Kafka官方文档翻译——设计
下面是博主的公众号,后续会发布和讨论一系列分布式消息队列相关的内容,欢迎关注. ------------------------------------------------------------ ...
- js验证input是否输入数字
onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execComma ...
- 【Android Developers Training】 51. 序言:打印内容
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- Python3.5学习笔记-文件操作
在Python中,操作文件对象使用open函数来创建,下表列出了常用的操作file的函数: 序号 方法及描述 1.file.close() 关闭文件.关闭后文件不能再进行读写操作. 2.file.fl ...
- c#面向对象-类(类及其构成)
学习c#已经快一个学期,在这一段时间里,通过自己的努力和老师指导,自己感觉收获颇丰,所以我想把自己学到东西整理一下,供大家点评!若有错误或不当之处,敬请指出. 今天,我先从类及其构成说起! 1. ...
- 解决java.lang.NumberFormatException: For input string: "id"
今天,项目突然报"java.lang.NumberFormatException:For input string:"id"",项目框架是spring,spri ...
- Python3控制结构与函数
1.if语句的另一种写法: expression1 if boolean_expression else expression2 boolean_expression为true时使用expressio ...
- red hat 6.5 红帽企业Linux.6.5 yum This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register. 解决办法
1.删除redhat原有的yum rpm -aq|grep yum|xargs rpm -e --nodeps 2.下载yum安装文件 wget http://mirrors.163.com/cent ...