XElement会自动将xmlns =""添加到自身

Zac*_*ach 21 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);
Run Code Online (Sandbox Code Playgroud)

上面的代码生成以下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>
Run Code Online (Sandbox Code Playgroud)

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

Dus*_*ges 12

您需要指定要添加的元素的名称空间.例如

//sample XElement populate Element from database
StateRequestRecordGUID = new XElement(xmlns + "StateRequestRecordGUID");
Run Code Online (Sandbox Code Playgroud)

//sample to add Elements to EmployerTPASeparationResponse
EmployerTPASeparationResponse = new XElement(xmlns + "EmployerTPASeparationResponse");
Run Code Online (Sandbox Code Playgroud)


Jef*_*tes 10

您需要为XElement添加它时指定命名空间,使其与XDocument.你可以这样做:

XElement employerTPASeperationResponse =
     new XElement(xmlns + "EmployerTPASeparationResponse");
Run Code Online (Sandbox Code Playgroud)

  • @Zach:添加上面的内容应该删除它,因为它位于已经指定它的元素下面.该架构为您处理该部分. (3认同)
  • 那很有效!现在我必须在每个添加元素的地方都包含xmlns +"ElementName".谢谢!! (3认同)
  • 关键是我不想在EmployerTPASeparationResponse中使用xmlns属性.有任何想法吗? (2认同)