xml选择下一个节点并更改该节点的值

时间:2013-09-04 07:25:36

标签: xml c#-4.0 linq-to-xml

我创建了这个xmlfile:

<?xml version="1.0" encoding="utf-8"?>
<Contacts xmlns:g="http://something.com">
  <Contact>
    <g:Phone>206-555-0144</g:Phone>
    <g:Name>Patrick Hines</g:Name>
    <g:Address>
      <street>this street</street>
    </g:Address>
  </Contact>
</Contacts>

我正在尝试选择手机节点,然后尝试获取下一个节点。电话节点是唯一的,所以我首先寻找这个。如何更改名称的值?

var doc = XDocument.Load("c:\\temp\\contacts.xml");
var reader = doc.CreateReader();
var namespaceManager = new XmlNamespaceManager(reader.NameTable);
namespaceManager.AddNamespace("g", g.NamespaceName);
var node = doc.XPathSelectElement("/Contacts/Contact/g:Phone[text()='206-555-0144']", namespaceManager);

var nd =node.NextNode // does not work

node.Value = "sjfjks";

2 个答案:

答案 0 :(得分:2)

首先,您的代码根本不编译。在问题行的末尾,你遗漏了;

更重要的是,您将node.NextNode指定给nd变量(指向<name>元素),但更改node.Value而不是nd!您首先应该为变量分配更多描述性名称!

我可以使用以下内容:

var phone = doc.XPathSelectElement("/Contacts/Contact/g:Phone[text()='206-555-0144']", namespaceManager);

// you have to cast NextNode to XElement to allow changing it's value
var name = (XElement)phone.NextNode;

// change name.Value instead of phone.Value!
name.Value = "test";

打印出的doc值看起来像预期的那样:

<Contacts xmlns:g="http://something.com">
  <Contact>
    <g:Phone>206-555-0144</g:Phone>
    <g:Name>test</g:Name>
    <g:Address>
      <street>this street</street>
    </g:Address>
  </Contact>
</Contacts>

答案 1 :(得分:0)

首先尝试添加根节点,然后如果仍然不起作用,请选择不带整个路径的Phone节点:

var doc = XDocument.Load("c:\\temp\\contacts.xml");
var reader = doc.CreateReader();
var namespaceManager = new XmlNamespaceManager(reader.NameTable);
namespaceManager.AddNamespace("g", g.NamespaceName);

var root = doc.Root; // set the Root of your document.

var node = root.XPathSelectElement("/Contacts/Contact/g:Phone[text()='206-555-0144']", namespaceManager); 
// if still doen't work try with 
// root.XPathSelectElement("//g:Phone[text()='206-555-0144']", namespaceManager);

var nd =node.NextNode;

node.Value = "sjfjks";