Search code examples
c#asp.netxmlxelement

I can't get <pmlcore:Sensor with XElement


I'm developing an ASP.NET MVC application with .NET Framework 4.5.1 that returns XML generated from database data.

I want to obtain this:

<?xml version="1.0" encoding="utf-8"?>
<pmlcore:Sensor [ Ommitted for brevety ] ">

But I get this:

<?xml version="1.0" encoding="utf-8"?>
<Sensor [ Ommitted for brevety ]  xmlns="pmlcore">

Reading all the answers found in Stackoverflow, I changed my code to use XNamespace:

XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
XDeclaration dec = new XDeclaration("1.0", "utf-8", null);

XNamespace pmlcore = "pmlcore";
XNamespace pmluid = "pmluid";

root = new XElement(pmlcore + "Sensor"
    , new XAttribute(XNamespace.Xmlns + "pmluid", 
        "urn:autoid:specification:universal:Identifier:xml:schema:1")
    , new XAttribute(XNamespace.Xmlns + "xsi", ns)
    , new XAttribute(XNamespace.Xmlns + "pmlcore", 
        "urn:autoid:specification:interchange:PMLCore:xml:schema:1")
    , new XAttribute(ns + "noNamespaceSchemaLocation",
                     "urn:autoid:specification:interchange:PMLCore:xml:schema:1 ./PML/SchemaFiles/Interchange/PMLCore.xsd")

How can I obtain <pmlcore:Sensor this?

If I use this code:

root = new XElement("pmlcore:Sensor"

I get this error:

The ':' character, hexadecimal value 0x3A, cannot be included in a name


Solution

  • The problem is that you're adding the wrong namespace... you're trying to use the alias for it, instead of the namespace URI. Here's a concrete example that works:

    using System;
    using System.Xml.Linq;
    
    class Program
    {
        static void Main(string[] args)
        {
            XNamespace pmlcore = "urn:autoid:specification:interchange:PMLCore:xml:schema:1";
            XNamespace pmluid = "urn:autoid:specification:universal:Identifier:xml:schema:1";
    
            var root = new XElement(pmlcore + "Sensor",
                 new XAttribute(XNamespace.Xmlns + "pmluid", pmluid.NamespaceName),
                 new XAttribute(XNamespace.Xmlns + "pmlcore", pmlcore.NamespaceName));
            Console.WriteLine(root);
        }
    }
    

    Output (reformatted):

    <pmlcore:Sensor
      xmlns:pmluid="urn:autoid:specification:universal:Identifier:xml:schema:1"
      xmlns:pmlcore="urn:autoid:specification:interchange:PMLCore:xml:schema:1" />