XElement会自动将xmlns =“”添加到自身

我正在从表创建一个新的XDocument。 我必须从XSD文档validation文档并且它会一直失败,因为它不应该将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文件。

    94321098761987654321323456109883   

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

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

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

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

您需要在添加XElement时为XElement指定名称空间,以使其与XDocument的名称空间匹配。 你可以这样做:

 XElement employerTPASeperationResponse = new XElement(xmlns + "EmployerTPASeparationResponse"); 

您必须为根元素创建一个XNamespace ,然后在创建元素时,将对象命名空间创建,如下所示:

 xmlDoc = new XDocument(); xmlDoc.Declaration = new XDeclaration("1.0", "utf-8", null); XNamespace pageDefinition = @"http://xmlns.oracle.com/adfm/uimodel"; XElement root = new XElement(pageDefinition + "pageDefinition", new XAttribute("Package", "oracle.webcenter.portalapp.pages")); xmlDoc.Add(root); 

上面的代码生成以下xml文件:

   

当您创建所有其他元素(EmployerTPASeparationResponse和StateRequestRecordGUID)时,您应该在name元素中包含命名空间(与创建EmployerTPASeparationResponseCollection时的方式相同)。