Home > Software engineering >  C# How remove single xml parent element node without removing the contents inside the parent node
C# How remove single xml parent element node without removing the contents inside the parent node

Time:07-30

I am new to C#, kindly help me. How to remove the single xml element node 'PaymentRecord' and content inside that should not get deleted.

  <Payments>
    <PaymentRecord>
      <PayId>2031</PayId>
      <Reference>Policy03</Reference>
      <StatusCode>ACV</StatusCode>
      <MethodDetail>
        <PaymentMethodDetail>
          <CardPaymentDetails>
            <CardHolderName>abcded</CardHolderName>
            <CardTransactionDetails>
              <StoredCard>N</StoredCard>
            </CardTransactionDetails>
          </CardPaymentDetails>
        </PaymentMethodDetail>
      </MethodDetail>
      <CurrencyCode>USD</CurrencyCode>
    </PaymentRecord>
  </Payments>

I need to remove "PaymentRecord" element from the XML. I need like below

  <Payments>
      <PayId>2031</PayId>
      <Reference>Policy03</Reference>
      <StatusCode>ACV</StatusCode>
      <MethodDetail>
        <PaymentMethodDetail>
          <CardPaymentDetails>
            <CardHolderName>abcded</CardHolderName>
            <CardTransactionDetails>
              <StoredCard>N</StoredCard>
            </CardTransactionDetails>
          </CardPaymentDetails>
        </PaymentMethodDetail>
      </MethodDetail>
      <CurrencyCode>USD</CurrencyCode>
  </Payments>

I have tried my below code, but its deleting the complete node which I don't want to do :- here 'queuePayload' is the xml element

XmlNodeList payloadRecordList = queuePayload.SelectNodes("//Payments/PaymentRecord");

foreach (XmlElement singleNode in payloadRecordList)
{
XmlHelper.removeElem((XmlElement)singleNode.ParentNode, "//PaymentRecord");

XmlDocument xmlDoc = singleNode.OuterXml;

// my remaining logic goes based on "xmldoc" value  - I will inserting this data to table

}

CodePudding user response:

You can use System.Xml.Linq with its XDocument to achiev this. Load the input and create a new document out of it like:

XDocument inputDoc = XDocument.Load(inputFile, LoadOptions.None);
XDocument outputDoc = new XDocument();
var elements = inputDoc.Element("Payments").Elements().Select(pr => pr.Elements());
XElement newElement = new XElement("Payments");
foreach (var element in elements)
{
    newElement.Add(element);
}
outputDoc.Add(newElement);
Console.WriteLine(outputDoc.ToString());

CodePudding user response:

I think @Fructzwerg is slightly overcomplicating it.

You can remove the PaymentRecord node and add all its children to the root in one go.

var xDoc = XDocument.Load(filePath);
var paymentRecord = xDoc.Root.Element("PaymentRecord");
var nodes = xDoc.Root.Element("PaymentRecord").Elements();
paymentRecord.Remove();
xDoc.Root.Add(nodes);
Console.WriteLine(xDoc.ToString());

dotnetfiddle

  • Related