【问题标题】:search for inner element, using Xpath or LINQ to XML使用 Xpath 或 LINQ to XML 搜索内部元素
【发布时间】:2011-10-27 22:50:11
【问题描述】:

我有如下的 XML

<?xml version="1.0" ?> 
<Hospital>
  <DR>
    <Salary>1000</Salary>
    <bonus> 3 </bonus>
  </DR>
  <Nurse>
    <Shift> </Shift>
  </Nurse>
</Hospital>

我想在 Dr 节点中搜索子元素,例如如果不存在插入它并更新文件,

还有如何使用 C# 更新 XML 版本

【问题讨论】:

    标签: xml xpath c#-3.0 linq-to-xml


    【解决方案1】:

    关于更新XML版本,目前微软的XML解析器和API只支持XML 1.0版本,不支持XML 1.1版本。

    至于检查DR元素是否没有foo子元素并添加一个你可以做例如

    XDocument doc = XDocument.Load("input.xml");
    XElement dr = doc.Root.Element("DR");
    if (dr.Element("foo") == null)
    {
      dr.Add(new XElement("foo", "..."));
    }
    doc.Save("output.xml"); // of course here you can overwrite the original file if needed
    

    【讨论】:

    • 如何给 foo 子元素添加属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多