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

时间:2019-02-12 06:14:58

标签: c# asp.net-mvc

我有以下格式的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>

如何添加元素?

2 个答案:

答案 0 :(得分:2)

您可以创建一个新节点并向其附加新节点,然后为每个子节点将该子节点附加到 节点:

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>

答案 1 :(得分:2)

谢谢:),我在下面的答案中找到了它,现在工作正常。

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