c# - XElement 自动将 xmlns =""添加到自身

标签 c# linq-to-xml xml-namespaces

我正在从表中创建一个新的 XDocument。我必须从 XSD 文档验证文档,但它一直失败,因为它在不应该的时候将 xmlns=""添加到元素之一。以下是相关代码的一部分。

    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
                XNamespace xmlns = "https://uidataexchange.org/schemas";
                XElement EmployerTPASeparationResponse = null;
                XElement EmployerTPASeparationResponseCollection = new XElement(xmlns + "EmployerTPASeparationResponseCollection", new XAttribute(XNamespace.Xmlns + "xsi", xsi), new XAttribute(xsi + "schemaLocation", "https://uidataexchange.org/schemas SeparationResponse.xsd"));
                XDocument doc = new XDocument(
                new XDeclaration("1.0", null, "yes"), EmployerTPASeparationResponseCollection);
    //sample XElement populate Element from database
    StateRequestRecordGUID = new XElement("StateRequestRecordGUID");
                        StateRequestRecordGUID.SetValue(rdr["StateRequestRecordGUID"].ToString());

    //sample to add Elements to EmployerTPASeparationResponse
    EmployerTPASeparationResponse = new XElement("EmployerTPASeparationResponse");
                    if (StateRequestRecordGUID != null)
                    {
                        EmployerTPASeparationResponse.Add(StateRequestRecordGUID);
                    }

    //the part where I add the EmployerTPASeparationResponse collection to the parent
    EmployerTPASeparationResponseCollection.Add(EmployerTPASeparationResponse);

以上代码生成以下 xml 文件。

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<EmployerTPASeparationResponseCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://uidataexchange.org/schemas SeparationResponse.xsd" xmlns="https://uidataexchange.org/schemas">
<EmployerTPASeparationResponse xmlns="">
    <StateRequestRecordGUID>94321098761987654321323456109883</StateRequestRecordGUID>
  </EmployerTPASeparationResponse>
</EmployerTPASeparationResponseCollection>

注意元素 EmployerTPASeparationResponse。它有一个空的 xmlns 属性。我想要发生的是只编写完全没有属性的 EmployerTPASeparationResponse。

最佳答案

您需要指定要添加的元素的 namespace 。例如

//sample XElement populate Element from database
StateRequestRecordGUID = new XElement(xmlns + "StateRequestRecordGUID");

//sample to add Elements to EmployerTPASeparationResponse
EmployerTPASeparationResponse = new XElement(xmlns + "EmployerTPASeparationResponse");

关于c# - XElement 自动将 xmlns =""添加到自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5955878/

相关文章:

c# - 实体管理器中自动生成的时间戳

c# - 使用 HttpClient PostAsJsonAsync 在 ASP.NET Core 中发送 HTTP POST 消息

c#-4.0 - 将 header 添加到 XDocument 和架构

c# - 如何使用 LINQ to XML 生成 xsi :schemalocation attribute correctly when generating a dynamic sitemap. xml?

html - CSS3 namespace 是否用于除 XML 之外的任何内容?

c# - 如何使用 XmlSerializer 反序列化具有多个 xmlns 属性的 XML

c# - 我可以在扩展方法中设置 decimal 变量的值吗?

c# - MIcrosoft Bot Framework 上的 session Bot 可能吗?

c# - 比较两个 xml 并使用 LINQ 打印差异

html - HTML,XMLNS, namespace ,XML