3

我正在使用 Linq to XML 和 C# 创建 XML。这一切都很好,除非我需要在 XML 中手动添加一行。仅当我有要传递给它的值时才添加此行,否则我将忽略整个标签。

我使用 XElement.Load 加载存储在字符串中的文本字符串,但是当我将其附加到 XML 时,它总是将 xmlns="" 放在标签末尾。

有没有办法告诉 XElement.Load 在将字符串放入 XML 时使用现有命名空间或忽略它?

理想情况下,我只想将我的字符串包含到正在创建的 XML 中,而无需添加额外的标签。

以下是我目前所做的示例:

string XMLDetails = null;
if (ValuePassedThrough != null)
XMLDetails = "<MyNewTag Code=\"14\" Value=\"" + ValuePassedThrough +"\"></MyNewTag>";

当我构建 XML 时,我将上面的字符串加载到我的 XML 中。正是在这里 xmlns="" 被添加到 XMLDetails 值中,但理想情况下我希望忽略它,因为它会在收件人尝试读取此标签时引起问题。

XNamespace ns = "http://namespace-address";
    XNamespace xsi = "http://XMLSchema-instance-address";

XDocument RequestDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement(ns + "HeaderTag",
        new XAttribute("xmlns", ns),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", "http://www.addressofschema.xsd"),
        new XAttribute("Version", "1"),
            new XElement(ns + "OpeningTAG",

...我的 XML 代码 ...

XElement.Load(new StringReader(XMLDetails))

... XML 代码结束 ...

正如刚才提到的。我的代码有效,它为我成功输出了 XML。它只是我使用 XElement.Load 加载的 MyNewTag 标记,将 xmlns="" 添加到它的末尾,这导致了我的问题。

有什么想法可以解决这个问题吗?谢谢你的帮助。

问候,丰富

4

2 回答 2

8

怎么样:

XElement withoutNamespace = XElement.Load(new StringReader(XMLDetails));
XElement withNamespace = new XElement(ns + withoutNamespace.Name.LocalName,
                                      withoutNamespace.Nodes());

作为一个更好的选择 - 为什么在构建 XML 时不包含名称空间,或者更好的是,创建一个XElement而不是手动生成一个 XML 字符串,然后再读取它。手动创建 XML 很少是一个好主意。除此之外,您假设它ValuePassedThrough已经被转义,或者不需要转义等。这可能是有效的 - 但这至少是一个值得关注的原因。

于 2009-09-21T09:26:47.420 回答
1

像这样

XElement XMLDetails = new XElement(ns + "OpeningTAG", new XElement(ns + "MyNewTag", new XAttribute("Code", 14), new XAttribute("Value", 123)));

XDocument RequestDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement(ns + "HeaderTag",
        new XAttribute("xmlns", ns),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", "http://www.addressofschema.xsd"),
        new XAttribute("Version", "1"),
            XMLDetails));
于 2009-09-21T09:56:13.373 回答