我正在从表中创建一个新的 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/