【问题标题】:Replacing Whole XmlElement with new value用新值替换整个 XmlElement
【发布时间】:2011-11-22 10:06:53
【问题描述】:

我在下面的代码中获取了 html,然后阅读了所有 imga 链接。请注意,这是 C# 2.0。

string xml = "<xhtml>" + inputXhtml + "</xhtml>";
XmlDocument node = new XmlDocument();
node.LoadXml(xml);
foreach (XmlElement element in TemplateUtilities.SelectNodes(node, "//html:img[@xlink:href]|//html:a[@xlink:href]"))
{
    bool flag = element.LocalName == "img";
    lStrCompLinkText = "";
    XmlAttributeCollection attributes = element.Attributes;
    XmlAttribute namedItem = (XmlAttribute)attributes.GetNamedItem("href", "http://www.w3.org/1999/xlink");
    string str2 = namedItem.Value;              
    Component currentObject = engine.GetObject(str2) as Component;
    if (flag)
    {
        element.SetAttribute("src", str2);
    }
    else
    {
        foreach (XmlNode xnode in element.ChildNodes)
        {
            lStrCompLinkText = lStrCompLinkText + xnode.OuterXml;
        }   
        string attr = ComponentBase.ComponentHelper.ComponentLinkAttributes(element, engine);       
        string compLink = ComponentBase.ComponentHelper.DisplayPublishedComponentLink(currentObject, lStrCompLinkText, attr, engine, package, pageObject);

        attributes.RemoveNamedItem("href", "http://www.tridion.com/ContentManager/5.0");
        //Here I want to replace whole element with the compLink
    }
    attributes.RemoveNamedItem("href", "http://www.w3.org/1999/xlink");
    attributes.RemoveNamedItem("type", "http://www.w3.org/1999/xlink");
    attributes.RemoveNamedItem("title", "http://www.w3.org/1999/xlink");
}

现在我想用新值 compLink 替换我的元素并添加回输入 HTML

请推荐

【问题讨论】:

    标签: c# xml c#-2.0


    【解决方案1】:

    在您的评论“// Here I want to replace”出现的地方执行以下操作。

    从 compLink 的内容创建一个 XML 文档(假设它是 XML)。

    XmlDocument xmlTemp = new XmlDocument();
    xmlTemp.loadXml( compLink );
    

    使用以下代码从其父元素中删除原始元素

    XmlNode ndParent = element.ParentNode;
    ndParent.RemoveChild( element);
    

    导入新的 xmlTemp 并将其附加到父级

    XmlNode ndImport = ndParent.OwnerDocument.ImportNode( xmlTemp.documentElement, true );
    ndParent.AppendChild( ndImport.CloneNode( true ) );
    

    【讨论】:

    • 嗨威廉..谢谢你的回复!!,我得到'链接'是一个未声明的命名空间。第 1 行,位置 2。因为我的 compLink 变量具有这种格式 下载路线图 (PDF) 请建议!!
    • 啊,命名空间,XML 中有史以来最糟糕的东西(但那是另一回事了……)。我会尝试将“链接”和“tcm”命名空间添加到父文档。将它们放在您创建 文档的顶部,例如 ,并从源文档中获取“url”的值。
    【解决方案2】:

    我使用以下逻辑解决了上述问题:

    XmlDocument lObjTCDCodeDom = new XmlDocument();
    lObjTCDCodeDom.LoadXml("<TCDCode/>");
    lObjTCDCodeDom.DocumentElement.InnerText = compLink;
    element.ParentNode.ReplaceChild(node.ImportNode(lObjTCDCodeDom.DocumentElement, true), element);
    

    然后进一步编写检查&lt;TCDCode/&gt; 并替换它的XSLT,然后我得到实际更新的xml。

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 2014-10-07
      • 1970-01-01
      • 2022-01-13
      • 2018-04-14
      • 2020-06-15
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      相关资源
      最近更新 更多