【问题标题】:ASP.net Creating an XLink node in and XDocumentASP.net 在和 XDocument 中创建 XLink 节点
【发布时间】:2011-02-12 11:52:35
【问题描述】:

我正在尝试以编程方式将新的 XLink 节点添加到 XDocument,但 .Net 似乎将它们创建为原子化命名空间和名称,我找不到任何代码将 XLink 节点添加到 XML?

我的代码如下所示:

//read in the current XML content
XDocument content = XDocument.Parse(xmlContent);

//add a new node called large images
XElement newNode = new XElement("large_images", "");
newNode.SetAttributeValue("{xmlns}xlink", "http://www.w3.org/1999/xlink");
newNode.SetAttributeValue("{xlink}type", "simple");
newNode.SetAttributeValue("{xlink}href", "tcm:5-550");
newNode.SetAttributeValue("{xlink}title", "of1_454x340.jpg");
content.Add(newNode);

不幸的是,这个 newNode 是这样的:

<large_images p1:xlink="http://www.w3.org/1999/xlink" p2:type="simple" p2:href="tcm:5-550" p2:title="of1_454x340.jpg" xmlns:p2="xlink" xmlns:p1="xmlns"></large_images>

但我需要节点看起来像这样才能通过 XML 验证:

<large_images xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="tcm:5-550" xlink:title="of1_454x340.jpg"></large_images>

有人可以帮忙吗?我不想走 String.Replace() 路线,因为这似乎必须是另一种可能的方式?

谢谢

瑞恩

【问题讨论】:

    标签: c# asp.net linq-to-xml xlink


    【解决方案1】:

    我会这样做:

    XNamespace ns = "http://www.w3.org/1999/xlink";
    
    XElement newNode = new XElement("large_images",
        new XAttribute(XNamespace.Xmlns + "xlink", ns),
        new XAttribute(ns + "type", "simple),
        new XAttribute(ns + "href", "tcm:5-550"),
        new XAttribute(ns + "title", "of1_454x340.jpg"));
    

    这会产生以下 XML:

    <large_images xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
        xlink:href="tcm:5-550" xlink:title="of1_454x340.jpg" />
    

    【讨论】:

    • 太完美了。非常感谢乔恩。
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多