簡體   English   中英

沒有命名空間的C#XElement

[英]C# XElement without namespace

我是Xdocument的新手,我需要您的幫助以了解我在做什么錯。

我有以下代碼:

static void Main(string[] args)
{

    XNamespace ns = "http://somesite.com";
    XNamespace schemalocation = "http://somesite/schema.xsd";
    XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
    XNamespace Xmlns = "http://www.w3.org/2001/XMLSchema-instance";
    var date = DateTime.Now;
    var guid = "urn:uuid:" + Guid.NewGuid();


    XDocument doc = new XDocument(
     new XElement(ns + "Message",
                  new XAttribute("id", guid),
                  new XAttribute("messageType", Properties.Settings.Default.messageType),
                  new XAttribute("dateTime", date),
                  new XAttribute("origin", Properties.Settings.Default.origin),
                  new XAttribute("originType", Properties.Settings.Default.originType),
                  new XAttribute("destination", Properties.Settings.Default.destination),
                  new XAttribute("userName", Properties.Settings.Default.userName),
                  new XAttribute("xmlns", ns.NamespaceName),
                  new XAttribute(XNamespace.Xmlns + "xsi", Xmlns),
                  new XAttribute(xsi + "schemaLocation", schemalocation),
                  new XElement ("Query",
                  new XElement("WhereClause", Properties.Settings.Default.WhereClause),
                  new XElement("ReturnStructure", Properties.Settings.Default.ReturnStructure)
                  )));

保存xml時,子元素“查詢”得到一個空的xmlns

<Query xmlns="">

我需要對代碼進行哪些更改才能獲得沒有名稱空間的“查詢”,因此它看起來像這樣:

<?xml version="1.0" encoding="utf-8"?>
    <Message id="urn:uuid:4ed742cf-1ee4-4548-9105-c230933cf473" messageType="Type" dateTime="datetime" origin="service" originType="type" destination="destination" userName="username" xmlns="http://somesite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://somesite/schema.xsd">
      <Query>
        <WhereClause>somequery</WhereClause>
        <ReturnStructure>somereturn</ReturnStructure>
      </Query>
    </Message>

謝謝您幫忙

拉斐爾

您需要將父命名空間添加到Query標記和Query標記的子標記中

new XElement (ns + "Query") 

new XElement (ns + "WhereClause")

new XElement (ns + "ReturnStructure")

因為一旦將名稱空間添加到Query中,子標記將不帶名稱空間,並且它們將顯示為空的名稱空間標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM