1

how to get xmlnode value based on attribute value in C#.

<Products>
  <Error>0</Error>
  <Product link="OWN">
    <ProductCode>CA</ProductCode>
    <ProductType>Account</ProductType>
    <ProductSubtype>Current Account</ProductSubtype>
    <ProductDescriptionEng>Current Account</ProductDescriptionEng>  
    <ProductNumber>1234567</ProductNumber>
    <ProductCurrency></ProductCurrency>
    <ProductCurrencyCode>01</ProductCurrencyCode>
    <ProductBalance>899293.003</ProductBalance>
    <LoanRef></LoanRef>
    <OldLoanRef></OldLoanRef>
    <ProductStandardID>00010001</ProductStandardID>
    <OldLoanRef></OldLoanRef>  
    <ProductStatusCode>00</ProductStatusCode>
    <ProductStatus>OPEN</ProductStatus>
    <ProductCategory>Deposit Account</ProductCategory>   
  </Product>
</Product>

in the above example i would like to get value of Product Link "OWN" based on passing attribute value (1234567) 1234567.

I have tried following code but it doesn't return value "OWN" from 'Product link" node.

string _accountsXml = GetProducts();
                _xmlDoc.LoadXml(_accountsXml);
                _productLinkType = _xmlDoc.SelectSingleNode(string.Format("//Products[../ProductNumber = '{0}']", prodNumber));

2 Answers 2

2

You do have to add code to get element's attribute value there, possibly minding the case when the right element was not found. Plus be careful with the element names - both in the xpath expression and in the XML.

The following test code would have "OWN" in the link variable:

var doc = XDocument.Parse(@"<?xml version=""1.0""?>  
<Products>
    <Error>0</Error>
    <Product link=""Global""/>
    <Product link=""OWN"">
        <Some/>
        <ProductNumber>1234567</ProductNumber>
        <Nodes/>
    </Product>
    <Product link=""External"">
        <ProductNumber>777</ProductNumber>
    </Product>
</Products>");

var id = 1234567;
var link = doc
    .XPathSelectElement($"//Product[ProductNumber = '{id}']")
    ?.Attribute("link")
    ?.Value;

Console.WriteLine($"Product link: {link ?? "not found"}");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks DK. Perfect. It works. Appreciate your help.
Thanks Pinaki. Appreciate. :)
1

Try this

_productLinkType = _xmlDoc.SelectSingleNode(string.Format("//Products[..//ProductNumber = '{0}']", prodNumber));

or

var xDoc = XDocument.Load(_accountsXml);
var productLinkType = xDoc.XPathSelectElement(string.Format("//Products[..//ProductNumber = '{0}']", prodNumber)).Element("Product").Attribute("link").Value;

The closing tag in your example is Product it should be Products

1 Comment

Thanks Pinaki. The second option "Or" code works. Appreciate your help.

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.