简体   繁体   中英

Find the value of an XML Element in C# when an attribute is attached to that Element

I have the following XML document to work with.

<ns0:ProductQuantity>
    <ns0:Measurement>
        <ns0:MeasurementValue>8500</ns0:MeasurementValue>
        <ns0:UnitOfMeasureCode Domain="UN-Rec-20">KG</ns0:UnitOfMeasureCode>
    </ns0:Measurement>
</ns0:ProductQuantity>

I have yet been unable to figure out how to read the value of "KG" from this document into a string in my C# code. I have extracted other element values, but none of them have this attribute of Domain="UN-Rec->20" attached to them. I am using Visual Studio 2013, and an idea of how I am currently extracting other data is as follows.

XmlDocument doc = new XmlDocument();
doc.Load(filePath);               
root = doc.DocumentElement;
prodAmt_xml[1] = root.GetElementsByTagName("ns0:MeasurementValue")[0].InnerText;

If anyone has any incite into this problem and a way to get these 'measurement units' I would be very grateful.

You need to take the XML namespace into account. ns0 isn't really part of the element name, it's a prefix that maps to a namespace (usually a URL).

Using Linq to XML and C# 6, assuming the URL for ns0 is http://foo.bar/ :

var doc = XDocument.Load(filePath);
var ns = XNamespace.Get("http://foo.bar/");
var unit = 
    doc.Descendants(ns + "ProductQuantity")
        .Elements(ns + "Measurement")
            .Elements(ns + "UnitOfMeasureCode")
            .Where(e => e.Attribute("Domain")?.Value == "UN-Rec->20")
            .Select(e => e.Value)
            .FirstOrDefault();

Note that ?. requires C# 6; if you're using an earlier version, you can also do this:

var doc = XDocument.Load(filePath);
var ns = XNamespace.Get("http://foo.bar/");
var unit = 
   (from e doc.Descendants(ns + "ProductQuantity")
              .Elements(ns + "Measurement")
              .Elements(ns + "UnitOfMeasureCode")
    let attr = e.Attribute("Domain")
    let domain = attr != null ? attr.Value : null
    where domain == "UN-Rec->20"
    select e.Value).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM