簡體   English   中英

如何在C#中向現有XML添加新的XmlElement?

[英]How to add a new XmlElement to existing XML in C#?

我有以下格式的XML:

(XmlDocument)JsonConvert.DeserializeXmlNode(requestBody, "root");

<root>
    <NumberActa>20659</NumberActa>
    <DegreeDate>09/10/2018</DegreeDate>
    <StudentList>
        <CostsCenter>ABK015q</CostsCenter>
        <DocumentType>C.C h.</DocumentType>
        <Names>LISSET MARCELA</Names>
    </StudentList>
    <StudentList>
        <CostsCenter>ABCDE</CostsCenter>
        <DocumentType>C.C h.</DocumentType>
        <Names>MARCELA</Names>
    </StudentList>
</root>

我有一個room元素,而不是這個元素,我需要添加<DA><DE></DE></DA>並且需要以下格式

   <DA>
      <DE>
        <NumberActa>20659</NumberActa>
        <DegreeDate>09/10/2018</DegreeDate>
        <StudentList>
            <CostsCenter>ABK015q</CostsCenter>
            <DocumentType>C.C h.</DocumentType>
            <Names>LISSET MARCELA</Names>
        </StudentList>
        <StudentList>
            <CostsCenter>ABCDE</CostsCenter>
            <DocumentType>C.C h.</DocumentType>
            <Names>MARCELA</Names>
        </StudentList>
       </DE>
    </DA>

如何添加元素?

您可以創建一個新節點並向其附加新節點,然后為每個子節點將該子節點附加到 節點:

string source= @" <root>
<NumberActa>20659</NumberActa>
<DegreeDate>09/10/2018</DegreeDate>
<StudentList>
    <CostsCenter>ABK015q</CostsCenter>
    <DocumentType>C.C h.</DocumentType>
    <Names>LISSET MARCELA</Names>
</StudentList>
<StudentList>
    <CostsCenter>ABCDE</CostsCenter>
    <DocumentType>C.C h.</DocumentType>
    <Names>MARCELA</Names>
</StudentList>
</root>";
var document = new XmlDocument();
document.LoadXml(source);
XmlNode oldRoot = document.SelectSingleNode("root");
XmlNode newRoot = document.CreateElement("DA");
XmlNode second = document.CreateElement("DE");

document.ReplaceChild(newRoot, oldRoot);
newRoot.AppendChild(second);

foreach (XmlNode childNode in oldRoot.ChildNodes)
{
    second.AppendChild(childNode.CloneNode(true));
}

var result = document.InnerXml;

結果:

<DA>
    <DE>
        <NumberActa>20659</NumberActa>
        <DegreeDate>09/10/2018</DegreeDate>
            <StudentList>
                <CostsCenter>ABK015q</CostsCenter>
                <DocumentType>C.C h.</DocumentType>
                <Names>LISSET MARCELA</Names>
            </StudentList>
            <StudentList>
                <CostsCenter>ABCDE</CostsCenter>
                <DocumentType>C.C h.</DocumentType>
                <Names>MARCELA</Names>
            </StudentList>
    </DE>
</DA>

謝謝:),我在下面找到了這個答案,現在工作正常。

XmlDocument XmldocNew = new XmlDocument();
XmlElement newRoot = XmldocNew.CreateElement("DE");
XmldocNew.AppendChild(newRoot);
//newRoot.InnerXml = doc.DocumentElement.InnerXml;
newRoot.InnerXml = doc.DocumentElement.OuterXml;

暫無
暫無

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

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