簡體   English   中英

使用LINQ添加和刪除XDocument元素及其子元素

[英]Adding and removing XDocument elements and their childs with LINQ

我一直在編寫一個使用XDocument編寫XML文件的程序。 測試程序的結構是:

<SchoolData storeName="mikveIsrael" location="mikve">
    <employee id="1">
        <personalInfo>
            <name>Ilan Berlinbluv</name>
            <zip>58505</zip>
        </personalInfo>
        <employeeInfo>
            <salary>5000</salary>
            <id>1</id>
        </employeeInfo>
    </employee>
    <employee id="2">
        <personalInfo>
            <name>Noam Inbar</name>
            <zip>58504</zip>
        </personalInfo>
        <employeeInfo>
            <salary>4500</salary>
            <id>2</id>
        </employeeInfo>
    </employee>
    <employee id="3">
        <personalInfo>
            <name>Adi Raiten</name>
            <zip>58503</zip>
            </personalInfo>
        <employeeInfo>
            <salary>5000</salary>
            <id>3</id>
        </employeeInfo>
    </employee>
</SchoolData>

到目前為止,我的測試程序將其寫入桌面上的Employee.xml。 我還可以使用XDocument.Load()從XML讀取數據,並解析不同的信息。 但是我不知道如何添加或刪除元素(我要添加的元素是<employee> ,其中包含所有元素,如名稱等。有人能指出我如何做到這一點的正確方向?

向XML添加元素非常簡單。 使用右縮進,您甚至可以在代碼中看到XML結構:

XDocument doc = XDocument.Load(fileName);

doc.Root.Add(new XElement("employee", new XAttribute("id", 42),
                 new XElement("personalInfo",
                     new XElement("name", "Arthur Dent"),
                     new XElement("zip", "00000")),
                 new XElement("employeeInfo",
                     new XElement("salary", 0),
                     new XElement("id", 3))));

doc.Save(fileName);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM