加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

向XML插入节点

发布时间:2020-12-16 05:07:49 所属栏目:百科 来源:网络整理
导读:1.假如现在有一个Xml文件,内容如下 ReportItems Line Name ="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 Heig

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读