在XML属性id中查找字符串的一部分并在C#中替换部分

时间:2015-07-08 07:27:32

标签: c# xml xpath

我有以下简单的XML文档:

<?xml version="1.0" encoding="utf-8"?>
<map title="enter map title here" id="_6cb8995f-430f-4422-918b-3042f6eda092">
  <topicref navtitle="Source" format="dita" id="_c2a73e14-2bbc-4730-88dc-0c4c699bd66e" scope="local" href="urn:ditastudio:topicreference:a2cec9de-d8e4-413e-ab1e-165a70c68adc">
    <topicref navtitle="Reference" format="dita" id="_18a0b17b-e5f0-4314-8536-d8152399f8d6" scope="local" href="urn:ditastudio:topicreference:7d25c6cc-b195-4968-af91-cd0d269f803b" />
  </topicref>
</map>

我想使用XPath来更改map//topicref/@href"中的部分href。我希望保留urn:ditastudio:topicreference:部分并用随机字符串替换后面的所有内容。

如何在C#中执行此操作?

到目前为止,这就是我正在做的事情......

foreach (Object map in mapList)
{
  XmlDocument theMap = new XmlDocument();
  theMap.XmlResolver = null;
  theMap.Load(map.ToString());

  String hrefPreText = "urn:ditastudio:topicreference:";
  String xPath = "/map//topicref/@href";


  foreach (string oldKey in OldToNewID_Dict.Keys)
  {
    String newVal = OldToNewID_Dict[oldKey];
    String newID = hrefPreText + newVal;

    XmlNode node = theMap.SelectSingleNode(xPath);
    node.Attributes[0].Value = newID;

    theMap.Save(map.ToString());
  }
}

我无法理解它。任何帮助都会受到欢迎!

1 个答案:

答案 0 :(得分:0)

假设您只想为map/topicref而不是map/topicref/topicref执行此操作(在这种情况下使用:XElement.Descendants("topicref")):

using System.Xml.XPath;
using System.Xml.Linq;

var xdocString = @"<?xml version="1.0" encoding="utf-8"?>
                    <map title="enter map title here" id="_6cb8995f-430f-4422-918b-3042f6eda092">
                      <topicref navtitle="Source" format="dita" id="_c2a73e14-2bbc-4730-88dc-0c4c699bd66e" scope="local" href="urn:ditastudio:topicreference:a2cec9de-d8e4-413e-ab1e-165a70c68adc">
                        <topicref navtitle="Reference" format="dita" id="_18a0b17b-e5f0-4314-8536-d8152399f8d6" scope="local" href="urn:ditastudio:topicreference:7d25c6cc-b195-4968-af91-cd0d269f803b" />
                      </topicref>
                    </map>";

XDocument xdoc = XDocument.Parse(xdocString);
String hrefPreText = "urn:ditastudio:topicreference:";

foreach (var topicref in xdoc.XPathSelectElements("map/topicref"))
{
    topicref.Attribute("href").Value = hrefPreText + "something random";
}

如果您想尝试使用此代码,请确保在"中转义""(替换为xdocString),如果我在此处执行此操作,则会弄乱格式化。