如何使用C#在XML中设置值?

时间:2013-09-17 06:16:05

标签: c# xml

如何使用c#更改以下xml文件中sourcePatientInfo的值。 我可以使用

读取值
var elem = (from n in xml.Descendants("Slot")
                        where n.Attribute("name").Value == "sourcePatientInfo"
                        select n).FirstOrDefault();

如何使用C#更改相同内容?

<?xml version="1.0" encoding="utf-8"?>
<rs:SubmitObjectsRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:rs="urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1" xmlns:rim="urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1" xmlns="urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1">
<LeafRegistryObjectList>
<ObjectRef id="urn:uuid:93606bcf-9494-43ec-9b4e-a7748d1a838d" />
<ExtrinsicObject id="Document01" mimeType="application/dicom" objectType="urn:uuid:7edca82f-054d-47f2-a032-9b2a5b5186c1">
  <Name>
    <LocalizedString value="Physical" />
  </Name>
  <Description />         
  <Slot name="sourcePatientId">
    <ValueList>
      <Value>pid1^^^&amp;1.2.3&amp;ISO</Value>
    </ValueList>
  </Slot>
  <Slot name="sourcePatientInfo">
    <ValueList>
      <Value>PID-3|pid1^^^&amp;1.2.3&amp;ISO</Value>
      <Value>PID-5|Doe^John^^^</Value>
      <Value>PID-7|19560527</Value>
      <Value>PID-8|M</Value>
      <Value>PID-11|100 Main St^^Metropolis^Il^44130^USA</Value>
    </ValueList>
  </Slot>

我想使用c#更改值。我无法弄明白。任何帮助解决此问题将不胜感激。

我想改变

 <Slot name="sourcePatientInfo">
 <ValueList>
 <Value>PID-3|pid1^^^&amp;1.2.3&amp;ISO</Value> 
 <Value>PID-5|Doe^John^^^</Value> 

以下值

 <Slot name="sourcePatientInfo"> 
 <ValueList> <Value>PID-3|MyPID</Value> 
 <Value>PID-5|MyName</Value>

我还尝试了以下代码,

 XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc1.NameTable);
 namespaceManager.AddNamespace("rs", "urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1");
 var query = "/rs:SubmitObjectsRequest/LeafRegistryObjectList/ExtrinsicObject";
 XmlNodeList nodeList = xmlDoc1.SelectNodes(query, namespaceManager);

 foreach (XmlNode node1 in nodeList)
 {
   if (node1.Attributes["Slot"].Value == "sourcePatientInfo")
   {
      node1.Attributes["ValueList"].Value = "Myvalue";
    }
  }

在此代码中,nodelist.count始终为零:-(。请帮我解决此问题。

2 个答案:

答案 0 :(得分:2)

如果您需要更新前两个值:

var slot = xml.Descendants("Slot")
              .Where(n => n.Attribute("name").Value == "sourcePatientInfo")
              .FirstOrDefault();
if(slot == null)                  
{
    throw new WhateverAppropriateHereEcxeption();
}
var values = slot.Descendants("Value").ToList();
if(values.Count < 2)                  
{
    throw new WhateverAppropriateHereEcxeption();
}
values[0].Value = "PID-3|MyPID"  // updating the first value
values[1].Value = "PID-5|MyName" // updating the second value

如果你必须按值搜索,你可以这样做:

bool UpdateValue(XElement slot, string oldValue, string newValue)
{
    var elem = slot.Descendants("Slot")
                   .Where(n => n.Name == "Value" && n.Value == oldValue)
                   .FirstOrDefault();
    if(elem != null)
    {
        elem = newValue;
        return true;
    }

    return false;
 }

并在一些功能中

 var slot = xml.Descendants("Slot")
               .Where(n => n.Attribute("name").Value == "sourcePatientInfo")
               .FirstOrDefault();
 if(slot == null)                  
 {
     throw new WhateverAppropriateHereEcxeption();
 }
 UpdateValue(slot, "PID-3|pid1^^^&amp;1.2.3&amp;ISO", "PID-3|MyPID");
 UpdateValue(slot, "PID-5|Doe^John^^^", "PID-5|MyName");

调用xml.Descendants("Slot") xml时,UPD仅查找默认命名空间中的元素。我使用扩展方法作为快速解决方法来避免这种情况:

public static IEnumerable<XElement> NsDescendants(this XContainer e, string elementName)
{
    return e.Descendants().Where(d => d.Name.LocalName == elementName);
}

答案 1 :(得分:0)

最后,我的问题通过以下代码解决。

XmlDocument xmlDocSOR = new XmlDocument();
XmlDocSOR.Load("filename.xml");
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocSOR.NameTable);
namespaceManager.AddNamespace("rs", "urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1");
namespaceManager.AddNamespace("ns", "urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1");
var query = "/rs:SubmitObjectsRequest/ns:LeafRegistryObjectList/ns:ExtrinsicObject/ns:Slot";
XmlNodeList nodeList = xmlDocSOR.SelectNodes(query, namespaceManager);

foreach (XmlNode plainnode in nodeList)
{
    if (plainnode.Attributes["name"].Value == "sourcePatientId")
    {
        XmlNode childnode = plainnode.LastChild;
        XmlElement ee1 = (XmlElement)childnode.FirstChild;
        ee1.InnerText = sPatientID;                      
     }
 }
 xmlDocSOR.Save("filename.xml");