web-dev-qa-db-ja.com

Linq toXML-XMLドキュメントのノードを更新/変更します

2つの質問があります:

1.私はLinq to XMLを使って作業しましたが、Linqを介してXMLドキュメントを変更できるかどうか疑問に思っています。つまり、何かのようなものがありますか

XDocument xmlDoc = XDocument.Load("sample.xml");

update item in xmlDoc.Descendants("item")
where (int)item .Attribute("id") == id
...

2.を使用して、新しいXMLElementを作成および追加する方法をすでに知っています。

xmlDoc.Element("items").Add(new XElement(......);

しかし、どうすれば単一のエントリを削除できますか?

XMLサンプルデータ:

<items>
  <item id="1" name="sample1" info="sample1 info" web="" />
  <item id="2" name="sample2" info="sample2 info" web="" />
</itmes>
21
knox

答えてくれてありがとう。すべてが正常に動作します。

私の質問との競争と同じように、以下のコードは単一のエントリを変更する方法を示しています。

string xml = @"<data><record id='1' info='sample Info'/><record id='2' info='sample Info'/><record id='3' info='sample Info'/></data>";
StringReader sr = new StringReader(xml);
XDocument d = XDocument.Load(sr);


d.Descendants("record").Where(x => x.Attribute("id").Value == "2").Single().SetAttributeValue("info", "new sample info");
16
knox

これはあなたが考えていることですか?

using System;
using System.Linq;
using System.Xml.Linq;

static void Main(string[] args)
{
    string xml = @"<data><record id='1'/><record id='2'/><record id='3'/></data>";
    StringReader sr = new StringReader(xml);
    XDocument d = XDocument.Load(sr);

    // the verbose way, if you will be removing many elements (though in
    // this case, we're only removing one)
    var list = from XElement e in d.Descendants("record")
               where e.Attribute("id").Value == "2" 
               select e;

    // convert the list to an array so that we're not modifying the
    // collection that we're iterating over
    foreach (XElement e in list.ToArray())
    {
       e.Remove();
    }

    // the concise way, which only works if you're removing a single element
    // (and will blow up if the element isn't found)
    d.Descendants("record").Where(x => x.Attribute("id").Value == "3").Single().Remove();

    XmlWriter xw = XmlWriter.Create(Console.Out);
    d.WriteTo(xw);
    xw.Flush();
    Console.ReadLine();
}
7
Robert Rossney

答えはこのスレッドにあります...あなたはそれらを見つけるためにたくさんのソートをしなければならないので、私はあなたのためにそれらをコンパイルする仕事をしました:

  1. はい、要素を編集できます
  2. 要素の削除は簡単です:element.Remove(); (その後、xDocumentを保存することを忘れないでください)

このスレッドを読んでいる場合は、要素を編集する方法を知りたいと思うでしょう。データをxmlに保存する方法は2つあります。例:

<tagName attributeName="some value">another value</tagName>
  1. タグの属性として
  2. タグの内容(読み取り値)として

属性の値を編集するために、knoxは彼自身の質問に答えました:

d.Descendants("record").Where(x => x.Attribute("id").Value == "2").Single().SetAttributeValue("info", "new sample info");

つまり、変更するXElementを取得し、element.SetAttributeValue( "AttributeName"、 "属性の新しい値")を呼び出します。

タグの値または内容を編集したい場合、Ajayはそれに答えました(彼のすべてのコードを掘り下げた場合):

persondata.Element("City").Value = txtCity.Text;

または、言い換えると、目的のXElementを取得したら、.Valueを使用して割り当てます。

メモリ内の要素に対してこれらの変更のいずれかを実行した後、それらの変更をディスクに永続化する場合は、XDocumentで.Save()を呼び出す必要があることに注意してください。

1
ctb

システムを使用する; System.Collections.Generic;を使用します。 System.Linqを使用する; System.Textを使用します。 System.Xml.Linqを使用します。 //System.Xmlを使用します;

名前空間XMLtoLinqApp {クラスプログラム{staticvoid Main(string [] args){

        //XmlDocument doc = new XmlDocument();
        //XmlElement newBook=doc.CreateElement("BookParticipant");
        //newBook.SetAttribute("Author");

        //Using Functional Construction to Create an XML Schema
        XElement xBookParticipant = new XElement("BookParticipant",
                                        new XElement("FirstName", "Joe"),
                                        new XElement("LastName", "Rattz"));
        Console.WriteLine(xBookParticipant.ToString());


        //Creates the Same XML Tree as Listing 6-1 but with Far Less Code
        XElement xBookParticipants = new XElement("BookParticipants",
                                        new XElement("BookParticipant",
                                        new XAttribute("type", "Author"),
                                        new XElement("FirstName", "Joe"),
                                        new XElement("LastName", "Rattz")),
                                        new XElement("BookParticipant",
                                        new XAttribute("type", "Editor"),
                                        new XElement("FirstName", "Ewan"),
                                        new XElement("LastName", "Buckingham")));
        Console.WriteLine(xBookParticipants.ToString());


        //-- Disadvatages of XML document
        //System.Xml.XmlElement xmlBookParticipant = new System.Xml.XmlElement("BookParticipant");
        XElement xeBookParticipant = new XElement("BookParticipant");


        XDocument xDocument = new XDocument(new XElement("BookParticipants",
                                            new XElement("BookParticipant",
                                            new XAttribute("type", "Author"),
                                            new XElement("FirstName", "Joe"),
                                            new XElement("LastName", "Rattz"))));
        Console.WriteLine(xDocument.ToString());


        //--Calling the ToString Method on an Element Produces the XML Tree
        XElement name = new XElement("Name", "Joe");
        Console.WriteLine(name.ToString());

        //--Console.WriteLine Implicitly Calling the ToString Method on an Element to Produce an XML Tree


        XElement name1 = new XElement("Person",
                                      new XElement("FirstName", "Joe"),
                                      new XElement("LastName", "Rattz"));
        Console.WriteLine(name1);

        //-- Casting an Element to Its Value’s Data Type Outputs the Value
        Console.WriteLine(name);
        Console.WriteLine((string)name);

        //--Different Node Value Types Retrieved via Casting to the Node Value’s Type
        XElement count = new XElement("Count", 12);
        Console.WriteLine(count);
        Console.WriteLine((int)count);

        XElement smoker = new XElement("Smoker", false);
        Console.WriteLine(smoker);
        Console.WriteLine((bool)smoker);

        XElement pi = new XElement("Pi", 3.1415926535);
        Console.WriteLine(pi);
        Console.WriteLine((double)pi);


        DeferredQryProblem();


        GenerateXMlFromLinqQry();

        WithoutReaching();

        Ancestors();


        AncestorsAndSelf();

        SortSample();

        FindElementwithSpecificChild();

    }

    private static void DeferredQryProblem()
    {
        XDocument xDocument = new XDocument(
                    new XElement("BookParticipants",
                    new XElement("BookParticipant",
                    new XAttribute("type", "Author"),
                    new XElement("FirstName", "Joe"),
                    new XElement("LastName", "Rattz")),
                    new XElement("BookParticipant",
                    new XAttribute("type", "Editor"),
                    new XElement("FirstName", "Ewan"),
                    new XElement("LastName", "Buckingham"))));
        IEnumerable<XElement> elements =
        xDocument.Element("BookParticipants").Elements("BookParticipant");
        foreach (XElement element in elements)
        {
            Console.WriteLine("Source element: {0} : value = {1}",
            element.Name, element.Value);
        }
        foreach (XElement element in elements)
        {
            Console.WriteLine("Removing {0} = {1} ...", element.Name, element.Value);
            element.Remove();
        }
        Console.WriteLine(xDocument);


        foreach (XElement element in elements)
        {
            Console.WriteLine("Source element: {0} : value = {1}",
            element.Name, element.Value);
        }
        foreach (XElement element in elements.ToArray())
        {
            Console.WriteLine("Removing {0} = {1} ...", element.Name, element.Value);
            element.Remove();
        }
        Console.WriteLine(xDocument);
    }

    //-- Creating an Attribute and Adding It to Its Element
    private static void CreatingAttribute()
    {
        XElement xBookParticipant = new XElement("BookParticipant", new XAttribute("type", "Author"));
        Console.WriteLine(xBookParticipant);
    }

    //--Creating a Comment with Functional Construction
    private static void CreatingComment()
    {
        XElement xBookParticipant = new XElement("BookParticipant",
                                                  new XComment("This person is retired."));
        Console.WriteLine(xBookParticipant);
    }

    //--Creating a Declaration with Functional Construction
    private static void CreateXmlDeclaration()
    {
        XDocument xDocument = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),

new XElement( "BookParticipant")); Console.WriteLine(xDocument); }

    private static void GenerateXMlFromLinqQry()
    {
        BookParticipant[] bookParticipants = new[] {new BookParticipant {FirstName = "Joe", LastName = "Rattz",
                                                    ParticipantType = ParticipantTypes.Author},
                                                    new BookParticipant {FirstName = "Ewan", LastName = "Buckingham",
                                                    ParticipantType = ParticipantTypes.Editor}
                                                    };
        XElement xBookParticipants =
        new XElement("BookParticipants",
                     bookParticipants.Select(p =>
                new XElement("BookParticipant",
                new XAttribute("type", p.ParticipantType),
                new XElement("FirstName", p.FirstName),
                new XElement("LastName", p.LastName))));


        Console.WriteLine(xBookParticipants);
    }

    //-- Obtaining Elements Without Reaching
    private static void WithoutReaching()
    {
        XDocument xDocument = new XDocument(new XElement("BookParticipants",
                                            new XElement("BookParticipant",
                                            new XAttribute("type", "Author"),
                                            new XElement("FirstName", "Joe"),
                                            new XElement("LastName", "Rattz")),
                                            new XElement("BookParticipant",
                                            new XAttribute("type", "Editor"),
                                            new XElement("FirstName", "Ewan"),
                                            new XElement("LastName", "Buckingham"))));

        //-- Simple Descendants
        IEnumerable<XElement> elements = xDocument.Descendants("BookParticipant");


        foreach (XElement element in elements)
        {
            Console.WriteLine("Element: {0} : value = {1}",
            element.Name, element.Value);
        }


        //-- Descendants with Where Clause
        IEnumerable<XElement> elements1 = xDocument.Descendants("BookParticipant")
                                                   .Where(e => ((string)e.Element("FirstName")) == "Ewan");
        foreach (XElement element1 in elements1)
        {
            Console.WriteLine("Element: {0} : value = {1}",
            element1.Name, element1.Value);
        }

    }


    //-- Ancestors Prototype
    private static void Ancestors()
    {
        XDocument xDocument = new XDocument(new XElement("BookParticipants",
                                            new XElement("BookParticipant",
                                            new XAttribute("type", "Author"),
                                            new XElement("FirstName", "Joe"),
                                            new XElement("LastName", "Rattz")),
                                            new XElement("BookParticipant",
                                            new XAttribute("type", "Editor"),
                                            new XElement("FirstName", "Ewan"),
                                            new XElement("LastName", "Buckingham"))));

        IEnumerable<XElement> elements = xDocument.Element("BookParticipants").Descendants("FirstName");
        // First, I will display the source elements.
        foreach (XElement element in elements)
        {
            Console.WriteLine("Source element: {0} : value = {1}",
            element.Name, element.Value);
        }
        // Now, I will display the ancestor elements for each source element.
        foreach (XElement element in elements.Ancestors())
        {
            Console.WriteLine("Ancestor element: {0}", element.Name);
        }


        // Now, I will display the ancestor elements for each source element.
        foreach (XElement element in elements.Ancestors("BookParticipant"))
        {
            Console.WriteLine("Ancestor element: {0}", element.Name);
        }

    }


    //-- AncestorsAndSelf
    private static void AncestorsAndSelf()
    {
        XDocument xDocument = new XDocument(
            new XElement("BookParticipants",
            new XElement("BookParticipant",
            new XAttribute("type", "Author"),
            new XElement("FirstName", "Joe"),
            new XElement("LastName", "Rattz")),
            new XElement("BookParticipant",
            new XAttribute("type", "Editor"),
            new XElement("FirstName", "Ewan"),
            new XElement("LastName", "Buckingham"))));
        IEnumerable<XElement> elements =
        xDocument.Element("BookParticipants").Descendants("FirstName");
        // First, I will display the source elements.
        foreach (XElement element in elements)
        {
            Console.WriteLine("Source element: {0} : value = {1}",
            element.Name, element.Value);
        }
        // Now, I will display the ancestor elements for each source element.
        foreach (XElement element in elements.AncestorsAndSelf())
        {
            Console.WriteLine("Ancestor element: {0}", element.Name);
        }


        // Now, I will display the ancestor elements for each source element.
        foreach (XElement element in elements.AncestorsAndSelf("BookParticipant"))
        {
            Console.WriteLine("Ancestor element: {0}", element.Name);
        }

    }


    //-- Sort Smaple

    private static void SortSample()
    {
        XElement root = XElement.Load("Data.xml");
        IEnumerable<decimal> prices =
            from el in root.Elements("Data")
            let price = (decimal)el.Element("Price")
            orderby price
            select price;
        foreach (decimal el in prices)
            Console.WriteLine(el);
    }

    //-- Find an Element with a Specific Child 
    private static void FindElementwithSpecificChild()
    {
        XElement root = XElement.Load("data.xml");
        IEnumerable<XElement> tests =
            from el in root.Elements("Data")
            where (int)el.Element("Quantity") > 3
            select el;
        foreach (XElement el in tests)
            Console.WriteLine((string)el.Attribute("TestId");
    }
}

}

http://msdn.Microsoft.com/en-us/library/bb387053.aspx

7.25-> A 3 24.50 B 1 89.99 A 5 4.95 A 3 66.00 B 10 .99 A 15 29.00 B 8 6.99

0
karthikeyan