【问题标题】:I can't get <pmlcore:Sensor with XElement我无法使用 XElement 获取 <pmlcore:Sensor
【发布时间】:2015-11-04 11:20:13
【问题描述】:

我正在使用 .NET Framework 4.5.1 开发一个 ASP.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")

我怎样才能获得&lt;pmlcore:Sensor这个?

如果我使用此代码:

root = new XElement("pmlcore:Sensor"

我收到此错误:

':' 字符,十六进制值 0x3A,不能包含在 名字

【问题讨论】:

    标签: c# asp.net xml xelement


    【解决方案1】:

    问题是您添加了错误的命名空间...您尝试为其使用 别名,而不是命名空间 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" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 2012-02-24
      相关资源
      最近更新 更多