0

I have an XML file with this structure :

<?xml version="1.0" encoding="utf-8"?>
<DocumentInterface transactionNo="0102014146" creationDate="2014-05-26" version="1.4" ilnSender="4306286000007" ilnRecipient="407731000008" creationTime="17:00:30" xsi:schemaLocation="http://xmlschema.metro-mgp.com/outdoc/DocumentInterface DocumentInterface.xsd" xmlns="http://xmlschema.metro-mgp.com/outdoc/DocumentInterface" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CheckSum>
    <DocCount>1</DocCount>
    <PayableAmount>682.38</PayableAmount>
</CheckSum>
 ......
    </DocumentInterface>

I need to modify the attribute transactionNo. From c# I try to get the value from file with this code:

       XmlDocument doc = new XmlDocument();
        using (FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
        {

            doc.PreserveWhitespace = true;
            doc.Load(fs);
        }

        XmlAttribute formTransactionNo = (XmlAttribute)doc.SelectSingleNode("//DocumentInterface/@transactionNo");
        if (formTransactionNo != null)
        {
             prmNewValue=formTransactionNo.Value;
        }

But always formTransactionNo is null.Can you help me to get this value? Thanks

1 Answer 1

2

You cannot select attribute with XPath. Actually you don't need XPath here - its easy to get attribute from root element:

XmlAttribute transactionNo = doc.DocumentElement.Attributes["transactionNo"];
string prmNewValue = transactionNo.Value;
// output: 0102014146

Updating attribute value is also simple:

transactionNo.Value = "007";
doc.Save(path_to_xml);

BTW consider to use modern LINQ to XML approach for parsing/updating xml. E.g. getting this attribute value will look like:

var xdoc = XDocument.Load(newFileName);    
var prmNewValue = (string)xdoc.Root.Attribute("transactionNo");

Or getting payable amount

var ns = xdoc.Root.GetDefaultNamespace();
var payableAmount = 
    (decimal)xdoc.Root.Element(ns + "CheckSum").Element(ns + "PayableAmount");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.