linq-to-xmllinq-to-xsd

Using C# and XDocument, how to I add xsi attributes into some Xml?


I need to fix Linq to Xsd so that it correctly handles arrays of elements of a global abstract complex type, of which there are multiple derived non-abstract types. It doesn't add the xsi namespace or mark up elements with their derived types. But first I need to learn how to do the following:

Using C# and XDocument, how can I add an xsi namespace and attributes to the following xml?

<?xml version="1.0" encoding="utf-8"?>
<Form>
  <References>
    <ReferenceID>0</ReferenceID>
    <ReferenceType>string</ReferenceType>
    <PermitNumber>string</PermitNumber>
  </References>
  <References>
    <ReferenceID>0</ReferenceID>
    <ReferenceType>string</ReferenceType>
    <CaseNumber>string</CaseNumber>
  </References>
</Form>

That's what I have, but this is what I need:

<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <References xsi:type="Permit">
        <ReferenceID>0</ReferenceID>
        <ReferenceType>String</ReferenceType>
        <PermitNumber>String</PermitNumber>
    </References>
    <References xsi:type="Case">
        <ReferenceID>0</ReferenceID>
        <ReferenceType>String</ReferenceType>
        <CaseNumber>String</CaseNumber>
    </References>
</Form>

Thanks,

James.


Solution

  • Just use XAttribute like this:

    ("original.xml" file contains your first xml)

    var xml = XDocument.Load("original.xml");
    
    XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
    var formNode = xml.Element("Form");
    formNode.Add(new XAttribute(XNamespace.Xmlns + "xsi", ns));
    
    var refs = formNode.Elements("References").ToList();
    refs[0].Add(new XAttribute(ns + "type", "Permit"));
    refs[1].Add(new XAttribute(ns + "type", "Case"));
    
    string target = xml.ToString();