2015-11-04 21 views
0

我正在開發一個.NET Framework 4.5.1的ASP.NET MVC應用程序,該應用程序返回從數據庫數據生成的XML。我無法獲得帶有XElement的<pmlcore:Sensor

我想獲得這樣的:

<?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"> 

閱讀所有#1中找到的答案,我改變了我的代碼使用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" 

我得到這個錯誤:

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

回答

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" />