用一组节点替换XML节点 [英] XML Replace node with a set of Nodes

查看:174
本文介绍了用一组节点替换XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常感谢您的帮助.我有这个样本xml文档.我想选择带有所有子元素的Address元素,并将其替换为 <Sam />.换句话说,我想用<Address> ……</Address>
替换<Sam />

Thanks for the help in advance. I have this sample xml document. I would like to select the Address element with all its children and replace it with <Sam />. In other words, I would like to replace <Sam /> with <Address> ……</Address>

<Contact>
    <Name>Patrick Hines</Name>
    <Phone>206-555-0144</Phone>
    <Address>
      <Street1>123 Main St</Street1>
      <City><city w:st="on"><place w:st="on">Mercer Island</place></city></City>
      <State>WA</State>
      <Postal>68042</Postal>
    </Address>
     <Date>
      <FirstDate>7/23/2011</FirstDate>
      <LastDate>6/20/2012</LastDate>
    </Date>
  <Sam />
  </Contact

推荐答案

好吧,从上面的最后一条评论中,我想我知道你想要什么. (这不是我想要的两种解释.)
首先,您的XPath表达式有点偏离.
然后,您只需要复制元素并将其添加到Sam元素中.
Ok, from your last comment above, I think I know what you want. (It isn''t either of the interpretations that I thought you wanted.)
First your XPath expression was off by a bit.
Then you just needed to copy the elements and Add them to the Sam element.
XDocument doc = XDocument.Load(filePath);
IEnumerable<XElement> Ad = doc.XPathSelectElements("/Contact/Address/*");
var sam = doc.XPathSelectElement("/Contact/Sam");
foreach (var item in Ad)
{
  var newItem = new XElement(item);
  sam.Add(newItem);
}


此时doc是:


At this point doc is:

<contact>
  <Name>Patrick Hines</Name>
  <Phone>206-555-0144</Phone>
  <Address>
    <Street1>123 Main St</Street1>
    <City>
      <city w:st="on">
        <place w:st="on">Mercer Island</place>
      </city>
    </City>
    <State>WA</State>
    <Postal>68042</Postal>
  </Address>
  <Date>
    <FirstDate>7/23/2011</FirstDate>
    <LastDate>6/20/2012</LastDate>
  </Date>
  <Sam>
    <Street1>123 Main St</Street1>
    <City>
      <city w:st="on">
        <place w:st="on">Mercer Island</place>
      </city>
    </City>
    <State>WA</State>
    <Postal>68042</Postal>
  </Sam>
</Contact>


附加说明:由于< City>的存在,这种XML设计并不理想,因为它很容易使人误读它.和< city>仅首字母的大小写不同.
如果可以的话,,我建议重新设计一下以提高可读性.


An additional comment: This XML design is not ideal in that it is easy for humans to mis-read it, due to the <City> and <city> that differ only by the case of the first letter.
If you can, I''d suggest redesigning this for better readability.


这篇关于用一组节点替换XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆