我无法获得<pmlcore:sensor with =“”xelement =“”

时间:2015-11-04 11:20:13

标签: c# asp.net xml xelement

=“”

我正在开发ASP。 .NET Framework 4.5.1的.NET MVC应用程序,它返回从数据库数据生成的XML。

我想获得这个:

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

但我明白了:

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

阅读Stackoverflow中的所有答案,我将代码更改为使用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")

我如何获得<pmlcore:Sensor这个?

如果我使用此代码:

root = new XElement("pmlcore:Sensor"

我收到此错误:

  

&#39;:&#39;字符,十六进制值0x3A,不能包含在a中   名称

1 个答案:

答案 0 :(得分:2)

问题是您添加了错误的命名空间...您正在尝试使用别名而不是命名空间URI。这是一个有效的具体例子:

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);
    }
}

输出(重新格式化):

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