Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

Update XML with C# using Linq

MY XML FILE STRUCTURE

<items>
  <item>
    <itemID>1</itemID>
    <isGadget>True</isGadget>
    <name>Star Wars Figures</name>
    <text1>LukeSkywalker</text1>
  </item>
</items>

TO READ DATA FROM XML BY ITEMID

XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("data.xml"));
var items = from item in xmlDoc.Descendants("item")
            where item.Element("itemID").Value == itemID
            select new
            {
                itemID = item.Element("itemID").Value,
                isGadget = bool.Parse(item.Element("isGadget").Value),
                name = item.Element("name").Value,
                text1 = item.Element("text1").Value,
             }

foreach (var item in items)
{
     ....
}

How to update XML data by itemID? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To update your xml use SetElementValue method of the XElement :

var items = from item in xmlDoc.Descendants("item")
    where item.Element("itemID").Value == itemID
    select item;

foreach (XElement itemElement in items)
{
    itemElement.SetElementValue("name", "Lord of the Rings Figures");
}

EDIT : Yes, I tried your example and it saves updated data to the file. Save your updated xml with Save method of the XDocument, here is the code that I tried :

string xml = @"<items>
           <item>
            <itemID>1</itemID>
            <isGadget>True</isGadget>
            <name>Star Wars Figures</name>
            <text1>LukeSkywalker</text1>
           </item>
        </items>";

XDocument xmlDoc = XDocument.Parse(xml);

var items = from item in xmlDoc.Descendants("item")
            where item.Element("itemID").Value == "1"
            select item;

foreach (XElement itemElement in items)
{
    itemElement.SetElementValue("name", "Lord of the Rings Figures");
}

xmlDoc.Save("data.xml");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...