【问题标题】:replace a specific text in XML (KML) file in r在 r 中替换 XML (KML) 文件中的特定文本
【发布时间】:2020-03-31 08:33:43
【问题描述】:

我有几个包含以下节点的 KML:

<description><![CDATA[<img src="image_23037733.png" height="400" width="1200" align ="middle" />]]></description>

我想将所有出现的文本“image_” 更改为“path/on/another/hdd/image_”。如何编辑以下代码来完成任务?

library(XML)

doc <- xmlTreeParse("File.kml", useInternal = TRUE)
nodes <- getNodeSet(doc, "description")
lapply(nodes, function(n) {
  xmlValue(n) <- gsub("image_","path/on/another/hdd/image_",xmlValue(n))
})


Error in `xmlValue<-`(`*tmp*`, value = "<img src=\"path/on/another/hdd/image_1.png\" height=\"400\" width=\"1200\" align =\"middle\" />") : 
  Cannot set the content of a node that is not an XMLInternalTextNode or a node containing a text node

【问题讨论】:

    标签: r xml kml gsub


    【解决方案1】:

    使用 Xml Linq:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication3
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.txt";
            static void Main(string[] args)
            {
                string input = "<root><description><![CDATA[<img src=\"image_23037733.png\" height=\"400\" width=\"1200\" align =\"middle\" />]]></description></root>";
                XDocument doc = XDocument.Parse(input);
    
                List<XCData> cdata = doc.DescendantNodes().Where(x => x.NodeType == XmlNodeType.CDATA).Select(x => (XCData)x).ToList();
                foreach (XCData c in cdata)
                {
                    string text = c.ToString();
                    text = text.Replace("image_", "path/on/another/hdd/image_");
                    c.ReplaceWith(text);
    
                }
    
            }
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 2021-01-02
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多