xml操作
来源:互联网 发布:深圳大数据产业协会 编辑:程序博客网 时间:2024/05/16 11:32
protected void Button1_Click(object sender, EventArgs e)
{
//为response(star)节点 和 Cabins(f) cabin节点分别添加个
string Response = "<TargetResponse> <Response mark=/"a/" test=/"E/"> <Cabins> <Cw C=/"L/" N=/"A/" D=/"75/" P=/"850/" K=/"6.5/" /> <Cw C=/"K/" N=/"A/" D=/"80/" P=/"900/" K=/"6.5/" /> </Cabins></Response> <Response mark=/"b/" test=/"E/"> <Cabins> <Cw C=/"H/" N=/"A/" D=/"80/" P=/"900/" K=/"5/" /> <Cw C=/"B/" N=/"A/" D=/"90/" P=/"1020/" K=/"5/" /> <Cw C=/"Y/" N=/"A/" D=/"100/" P=/"1130/" K=/"5/" /> <Cw C=/"F/" N=/"A/" D=/"150/" P=/"1700/" K=/"6.4/" /> </Cabins> </Response></TargetResponse>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(Response);
XmlNodeList xnlist = xmlDoc.SelectSingleNode("TargetResponse").ChildNodes;
foreach (XmlNode xn in xnlist)
{
XmlElement xnResponse = (XmlElement)xn;
XmlNodeList xnCabins = xn.SelectSingleNode("Cabins").ChildNodes;
XmlAttribute attrstart = xmlDoc.CreateAttribute("star");//创建节点
XmlAttribute attrCabin = xmlDoc.CreateAttribute("F");//创建节点
string scity = "";
foreach (XmlNode xmlnode in xnCabins)
{
XmlAttribute attrF = xmlDoc.CreateAttribute("F");
XmlElement xmlelement = (XmlElement)xmlnode;
//给相应的节点赋值
attrF.Value = xnResponse.Attributes["mark"].Value;
attrCabin.Value = xnResponse.Attributes["mark"].Value;
xmlnode.Attributes.Append(attrF);
xmlnode.ParentNode.Attributes.Append(attrCabin);
scity = "f";
}
attrstart.Value = scity;
xn.Attributes.Append(attrstart);
}
string newa = xmlDoc.OuterXml;
XmlNodeList nodlist = xmlDoc.SelectSingleNode("/TargetResponse").ChildNodes;
if (nodlist != null)
{
foreach (XmlNode xnod in nodlist)
{
string mark = xnod.Attributes["mark"].Value;
string test = xnod.Attributes["test"].Value;
XmlNodeList cabinnodelist = xnod.SelectSingleNode("//Cabins[@F='" + mark + "']").ChildNodes;
for (int i = 0; i < cabinnodelist.Count; i++)
{
int d = Convert.ToInt32(cabinnodelist[i].Attributes["D"].Value);
int p = Convert.ToInt32(cabinnodelist[i].Attributes["P"].Value);
if (cabinnodelist[i].Attributes["Y"] == null)
{
XmlAttribute Y = xmlDoc.CreateAttribute("Y");
cabinnodelist[i].Attributes.Append(Y);
}
if (cabinnodelist[i].Attributes["C"].Value == "L")
{
cabinnodelist[i].Attributes["Y"].Value =( d + p).ToString();
}
}
}
}
}
/// <summary>
/// 添加子元素(XML)
/// </summary>
/// <param name="doc">xml文档对象</param>
/// <param name="nodeParent">父节点元素</param>
/// <param name="strTag">子节点名称</param>
/// <param name="strValue">子节点值</param>
/// <returns>子节点元素</returns>
public static XmlElement AddTextElement(XmlDocument doc,
XmlElement nodeParent,
string strTag,
string strValue)
{
#region 添加子元素
//通过传入的标签,创建一个新元素
XmlElement nodeElem = doc.CreateElement(strTag);
//通过传入的值,创建一个文本节点
XmlText nodeText = doc.CreateTextNode(strValue);
// 将此元素作为一个子元素添加到一个元素上
nodeParent.AppendChild(nodeElem);
// 将文本节点添加到此元素的子节点中
nodeElem.AppendChild(nodeText);
return nodeElem;
#endregion
}
model.PNR = Convert.ToString(xmlDoc.GetElementsByTagName("PNR").Item(0).InnerText);