1

我的 XML 文件是:

<?xml version="1.0" encoding="utf-8" ?>
<people>
<person
index="1"
name="Zlecenie numer jeden"
beneficiary="Kowalski"
description="Proste zlecenie jakiejs strony czy cos"
price="800"
deadline="27.12.2013" />
</people>

How can I add to this existing file, something like new record:

<person
index="4"
name="Zlecenie numer cztery"
beneficiary="Kowalski"
description="Proste zlecenie jakiejs strony czy cos"
price="800"
deadline="27.12.2013" />

或删除,或者如果您知道如何更新现有记录,那么这也是。谢谢

4

2 回答 2

0

尝试下一个将元素添加到 xml 中的代码片段。请注意,我使用 xml 作为带有转义字符的字符串。你可能有xml文件

var str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<people>\r\n<person\r\nindex=\"1\"\r\nname=\"Zlec" +
"enie numer jeden\"\r\nbeneficiary=\"Kowalski\"\r\ndescription=\"Proste zlecenie jakiejs " +
"strony czy cos\"\r\nprice=\"800\"\r\ndeadline=\"27.12.2013\" />\r\n</people>";

var xml = XElement.Parse(str);
var newNode = new XElement("person", 
                    new XAttribute("index", 4),
                    new XAttribute("name", "Zlecenie numer cztery"),
                    new XAttribute("beneficiary", "Kowalski"),
                    new XAttribute("description", "Proste zlecenie jakiejs strony czy cos"),
                    new XAttribute("price", 800),
                    new XAttribute("deadline", "27.12.2013"));

xml.Add(newNode);

//you can store whole xml tree in one variable simply by calling ToString on xml
str = xml.Tostring();

Console.WriteLine(str);

印刷:

<people>
  <person index="1" name="Zlecenie numer jeden" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
  <person index="4" name="Zlecenie numer cztery" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
</people>
于 2013-01-08T16:12:11.310 回答
0
XDocument xdoc = XDocument.Load(xmlFileName);

void Update(XDocument xdoc )
{
     XElement repser = doc.Root.Element("people").Elements("person").Where(r => (int)r.Attribute("index") = xdoc.index).FirstOrDefault();
    if (repser != null)
    {
        // update
        repser.SetAttribute("name", xdoc.name);
        repser.SetAttribute("beneficiary", xdoc.beneficiary);
        repser.SetAttribute("description", xdoc.description);
        repser.SetAttribute("price", xdoc.price);
        repser.SetAttribute("deadline", xdoc.deadline);
        // and so on
     }
     else
     {
        //insert
        doc.Root.Element("people").Add
           new XElement("person",
             new XAttribute("index", xdoc.id),
             new XAttribute("name", xdoc.name),
             new XAttribute("beneficiary", xdoc.beneficiary),
             new XAttribute("description", xdoc.description),
             new XAttribute("price", xdoc.price),
             new XAttribute("deadline", xdoc.deadline)
             // and so on
           ));
      }
}

您可以在 else 语句中手动插入 XAttribute 值中的值以进行更新。

于 2013-01-08T16:24:26.097 回答