我使用LINQ到XML和C#创建XML。这一切都只是当我需要手动添加一行在XML的伟大工程。如果我有一个值,以通过将其该行仅添加,否则我只是忽略整个标签。

我用XElement.Load文本字符串,我存储在一个字符串,但在加载时,我将其连接到它总是在XMLNS放XML =“”在我的结束标记。

有没有一种方法,我可以告诉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我。它只是MyNewTag标签我使用XElement.Load得到的xmlns =加载“”加入到它的结束,这是造成我的问题。

任何想法如何,我可以解决此问题?感谢您的帮助。

此致 富

有帮助吗?

解决方案

如何:

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

作为一个更好的选择 - 你为什么不包含任何命名空间,当你建立了XML,甚至更好,创建一个XElement而不能手动生成一个XML字符串,然后您再进行读取。手动创建XML是很少一个好主意。除了别的,你假定ValuePassedThrough已经逃脱了,或者不需要逃逸等那的可能的是有效的 - 但它至少引起人们的关注。

其他提示

筛选

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));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top