【发布时间】:2019-12-02 08:51:47
【问题描述】:
我的目标是创建一个XML node,它有两个attributes - 一个是namespace,另一个是prefix,其中namespace,如下所示:
到目前为止,我已经尝试了 3 个选项:
选项 1:硬编码,不起作用。
XElement paymentmethodType = XElement.Parse("<PaymentMethod xmlns:xsi=\"w3.org/2001/XMLSchema-instance\" xsi:type=\"CreditTransferType\"/>");
我只知道这个:
<PaymentMethod xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" type="CreditTransferType">
选项 2:将我的结构与 XmlAttributes 和 XMlNodes 一起使用:
XmlAttribute paymentmethodNamespace = CreateAttribute(paymentMethod, "xmlns:xsi", "http://w3.org/2001/XMLSchema-instance");
XmlAttribute paymentmethodType = CreateAttribute(paymentMethod, "xsi:type", "CreditTransferType");
public XmlAttribute CreateAttribute(XmlNode parentNode, string attributeName, string attributeValue)
{
var attribute = parentNode.OwnerDocument.CreateAttribute(attributeName);
attribute.Value = attributeValue;
parentNode.Attributes.Append(attribute);
// parentNode.AppendChild(node);
return attribute;
}
我又明白了:
<PaymentMethod xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" type="CreditTransferType">
选项 3:XElement 和 XAttributes:
XElement paymentMethod = new XElement("PaymentMethod",
new XAttribute(XNamespace.Xmlns + "xsi", "http://w3.org/2001/XMLSchema-instance"),
new XAttribute(XNamespace.Xmlns + "xsi:type", "CreditTransferType"));
但我得到一个Exception,“:”不是一个有效的符号。这也是一个问题,因为我使用XMlDocument,它只适用于XMlNode 和XMlAttribute。它不适用于XAttribute。
现在我有超过 400 行代码,我只想设置这个命名空间,我已经完成了文档。有没有简单的方法?
【问题讨论】:
-
您的选项 1 有效。有什么问题?
-
嗨,jdweng。它没有得到 xsi:type 它只是得到类型,因此 Web 服务拒绝该文档。
-
我在代码后面放了一个断点,然后将鼠标悬停在 paymentmethodType 上并选择箭头并查看 XML,它与输入相匹配。不确定您的观看方式。
-
是的,代码显示它很好。但是,当您将其保存到 XML 时,它不会保存在 xml 本身中。
标签: c# xml namespaces attributes