skip to Main Content

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

}

2

Answers


  1. 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());
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search