是否能够对xml进行增删改

fightfordream1 2011-03-04 12:56:41

<?xml version="1.0" encoding="utf-8" ?>
<Table>
<node ID="1" PintName="abc" objectId="87678" FunctionId="1"/>
<node ID="2" PintName="def" objectId="39392" FunctionId="1"/>
<node ID="3" PintName="ghi" objectId="996378" FunctionId="2"/>
<node ID="4" PintName="jkl" objectId="43232" FunctionId="2"/>
<node ID="5" PintName="mnl" objectId="321323" FunctionId="2"/>
</Table>


问题1:增—>比如增加一条<node ID="6"intName="opq" objectId="23432" FunctionId="3"/>,代码应该如何写?

问题2:删—>比如删除第三行(既条件为ID=3)的记录—>既删除<node ID="3" PintName="ghi" objectId="996378" FunctionId="2"/>

问题3:改—>修改某字段的值,比如修改第二行(条件是ID为2)的PointName字段值(比如将def改成abc)

PS:查询的代码已经有了,如下—>

string xmlPath = Application.StartupPath;
xmlPath = xmlPath.Replace("bin\\Debug", "XMLFile1.xml");
XDocument xdoc = XDocument.Load(xmlPath);

var query = from x in xdoc.Descendants("node")
where x.Attribute("FunctionId").Value == "2"
select x.Attribute("PintName").Value;

foreach (var q in query)
{
_PointName2.Add(q);
}
...全文
220 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
z050301402 2011-03-04
  • 打赏
  • 举报
回复
肯定可以三
querystringcom 2011-03-04
  • 打赏
  • 举报
回复
可以的 可以用xmldocument对他进行操作
yiyioo 2011-03-04
  • 打赏
  • 举报
回复
完全没有问题~
机器人 2011-03-04
  • 打赏
  • 举报
回复

// 增加node节点
xdoc.Descendants("Table").FirstOrDefault().Add(
new XElement("node",
new XAttribute("ID", "1"),
new XAttribute("PintName", "ttt"),
new XAttribute("objectId", "3333333"),
new XAttribute("FunctionId", "3")));
xdoc.Save(xmlPath);
// 删除Id=3的node节点
var node1 = xdoc.Descendants("node").Where(x => x.Attribute("ID").Value == "3").FirstOrDefault();
if (node1 != null)
node1.Remove();
xdoc.Save(xmlPath);
// 修改Id=2的node节点
var node2 = xdoc.Descendants("node").Where(x => x.Attribute("ID").Value == "2").FirstOrDefault();
if (node2 != null)
node2.Attribute("PintName").Value = "abc";
xdoc.Save(xmlPath);

  • 打赏
  • 举报
回复
传统的方法
Asp.Net XML操作基类(修改,删除,新增,创建)

Linq To XML
XDocument inventoryDoc =
new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("Current Inventory of AutoLot"),
new XElement("Inventory",
new XElement("Car", new XAttribute("ID", "1"),
new XElement("Color", "Green"),
new XElement("Make", "BMW"),
new XElement("PetName", "Stan")
),
new XElement("Car", new XAttribute("ID", "2"),
new XElement("Color", "Pink"),
new XElement("Make", "Yugo"),
new XElement("PetName", "Melvin")
)
)
);
// Display the document and save to disk.
Console.WriteLine(inventoryDoc);
inventoryDoc.Save("SimpleInventory.xml");
}

wuyq11 2011-03-04
  • 打赏
  • 举报
回复
XDocument xdoc = XDocument.Load(Server.MapPath("a.xml"));
//删除
xdoc.Element("").Element("").Remove();

XElement xe = new XElement("", "");
//将添加到指定元素的最后面
xdoc.Element("").Element("").Add(xe);
LINQ TO XML
anbin0814 2011-03-04
  • 打赏
  • 举报
回复
增删查改都可以
传送门
cjh200102 2011-03-04
  • 打赏
  • 举报
回复
可以对XML进行这些操作

110,579

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧