代码之家  ›  专栏  ›  技术社区  ›  Richard Reddy

使用XElement.Load时如何添加(或忽略)XML命名空间

  •  3
  • Richard Reddy  · 技术社区  · 17 年前

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

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

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

    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))
    

    有没有办法解决这个问题?谢谢你的帮助。

    2 回复  |  直到 17 年前
        1
  •  8
  •   Daniel Hilgarth Richard    13 年前

    怎么样:

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

    作为一个更好的选择——为什么不在构建XML时包含名称空间,或者更好地创建一个 XElement 而不是手动生成XML字符串,然后读取该字符串。手动创建XML很少是个好主意。除此之外,你认为 ValuePassedThrough 已经逃跑了,或者不需要逃跑等等 也许 要有道理——但这至少是一个值得关注的问题。

        2
  •  1
  •   dmportella Balazs Tihanyi    17 年前

    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));