gpt4 book ai didi

没有命名空间的 C# XElement

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:27 24 4
gpt4 key购买 nike

我是 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="">

我需要对我的代码做哪些更改才能在没有 namespace 的情况下获得“查询”,因此它看起来像这样:

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

谢谢你的帮助

拉斐尔

最佳答案

您需要将父命名空间添加到查询标签和查询标签的子标签中

new XElement (ns + "Query") 

new XElement (ns + "WhereClause")

new XElement (ns + "ReturnStructure")

因为一旦您将命名空间添加到 Query 中,子标签将没有命名空间,并且它们将显示为空的命名空间标签。

关于没有命名空间的 C# XElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46933367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com