向XML插入节点

前端之家收集整理的这篇文章主要介绍了向XML插入节点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.假如现在有一个Xml文件内容如下

<ReportItems>
<LineName="line2">
<Top>3.75cm</Top>
<Width>0.2381cm</Width>
<Style>
<BorderStyle>
<Default>Solid</Default>
</BorderStyle>
<FontFamily>宋体</FontFamily>
</Style>
<ZIndex>2</ZIndex>
<Left>3.75cm</Left>
<Height>0.50265cm</Height>
</Line>
</ReportItems>

2.现需要向下面的Xml文件内容的ReportItems节点下添加内容,变成下面的样子:

<ReportItems>
<TextBoxName="textBox1">
<Top>1.5cm</Top>
<Width>2.75cm</Width>
<Style>
<FontFamily>宋体</FontFamily>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
<ZIndex>4</ZIndex>
<CanGrow>true</CanGrow>
<Left>20.25cm</Left>
<Height>2.25cm</Height>
<Value>HelloWorld</Value>
</TextBox>
<LineName="line1">
<Top>3.75cm</Top>
<Width>0.2381cm</Width>
<Style>
<BorderStyle>
<Default>Solid</Default>
</BorderStyle>
<FontFamily>宋体</FontFamily>
</Style>
<ZIndex>2</ZIndex>
<Left>3.75cm</Left>
<Height>0.50265cm</Height>
</Line>
</ReportItems>

3.转换代码如下:

stringfile=File.ReadAllText(filePath);//filePath是Xml存放的完整路径
TextReadertextReader=newStringReader(file);
XElementdoc
=XElement.Load(textReader);
XElementnode
=doc.Descendants().Where(c=>c.Name.LocalName=="ReportItems").First();//Name是包含命名空间的,LocalName不包含
XNamespacens=doc.Name.NamespaceName;
XElemente
=newXElement(ns+"TextBox",newXAttribute("Name","textBox1"),//为节点添加属性
newXElement(ns+"Top","1.5cm"),//在每个节点的名称前都要加上命名空间,不然会有xmlns:""的属性出现
newXElement(ns+"Width","2.75cm"),
newXElement(ns+"Style",
newXElement(ns+"FontFamily","宋体"),
newXElement(ns+"PaddingLeft","2pt"),
newXElement(ns+"PaddingRight",
newXElement(ns+"PaddingTop",
newXElement(ns+"PaddingBottom",
newXElement(ns+"Color","#FFFFFF"),
newXElement(ns+"BackgroundColor","#3F2FAF"),
newXElement(ns+"FontSize","5pt")),
newXElement(ns+"ZIndex","4"),
newXElement(ns+"CanGrow","true"),
newXElement(ns+"Left","20.25cm"),
newXElement(ns+"Height","2.25cm"),
newXElement(ns+"Value","HelloWorld"));

node.Add(e);
//追加构造好的节点
doc.Save(filePath);//保存到文件

转载自:

http://www.cnblogs.com/cdts_change/archive/2010/03/16/1686869.html

原文链接:https://www.f2er.com/xml/299219.html

猜你在找的XML相关文章