0

Consider the following two pieces from an XSD.

1.

<xs:complexType name="CurrencyAndAmount">
    <xs:simpleContent>
        <xs:extension base="ActiveOrHistoricCurrencyAndAmount_SimpleType">
            <xs:attribute name="Ccy" type="CurrencyCode" use="optional"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

2.

<xs:simpleType name="CurrencyCode">
    <xs:restriction base="xs:string">
        <xs:maxLength value="3"/>
        <xs:pattern value="[A-Z]{3,3}"/>
    </xs:restriction>
</xs:simpleType>

I have the value of the "type" attribute in the first complexType element group. I am trying to get the element group where the "name" attribute has the same value than the the "type" attribute in group 1.

I have this LINQ query...

IEnumerable<XElement> a = xsdDocument.Descendants()
                         .Where(x => x.Attribute("name").Value == "CurrencyCode");

... but it throws a NullReferenceException

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rico Strydom
  • 537
  • 1
  • 6
  • 26
  • I'm not much of an XML expert... but isn't `x.Attribute("name").Value` equal to "Ccy"?. Would it make sense to change that to `x.Attribute("type").Value`, which is equal to "CurrencyCode"? – Sean Sailer Jul 03 '19 at 14:47
  • Rather than reading the schema as XML and interpreting that, just read it as an `XmlSchema` and use the facilities that provides. – Jeff Mercado Jul 03 '19 at 15:57
  • 2
    If the attribute (in this case, `name`) is not present then the `Attribute` method will return a `null`, so you can't de-reference it to access `Value`. You could do a null conditional, `x.Attribute("name")?.Value`. – NetMage Jul 03 '19 at 18:31
  • @NetMage, in this case the value is present. Does this exception perhaps occur at another group somewhere else in my xsd where the attribute is not present? Your piece of code did offer a solution to my problem. Thanks! – Rico Strydom Jul 04 '19 at 05:15
  • 2
    It doesn't matter, you're iterating over the descendants which is all elements in the document. Not every element contains a name attribute so you will inevitably come across a case where `x.Attribute("name")` is null. – Jeff Mercado Jul 08 '19 at 16:30

0 Answers0