繁体   English   中英

从网络服务读取XML,然后根据其属性值删除子元素,然后将其写回到

[英]read XML from a webservice remove a child element based on the value of its attribute it and write it back to the

可以说以下是我使用此代码从Web服务接收到的xml输入:

string url = txtURL.Text;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
XmlDocument doc = new XmlDocument();
doc.Load(rep.GetResponseStream());
rep.Close();

现在我在“文档”中有以下xml文档

<note>
<parent_element>
<child_element attribute_1="1">
<inner_element> first Text </inner_element>
</child_element>
<child_element attribute_1="2">
<inner_element> second Text </inner_element>
</child_element>
</parent_element>
</note>

现在,我想根据其属性值删除第一个子元素。 因此,如果子元素的属性值为“ 1”,那么我想删除“ child_element”及其所​​有子元素。 所以我的最终结果应如下所示:

<note>
<parent_element>
<child_element attribute_1="2">
<inner_element> second Text </inner_element>
</child_element>
</parent_element>
</note>

删除元素后,我将其写回到Web服务。 我知道我要很多,但到目前为止还不能弄清楚。 我会包含我的代码,但是由于我是xml操作的新手,所以我认为这没有用(悲伤)。 任何帮助或指示,将不胜感激。

感谢大伙们。

首先: doc.load(txtURL.Text)足以从远程位置加载XML。

您可以像这样删除节点:

XmlDocument doc = new XmlDocument();
doc.Load(filename);

//Select node that needs to be deleted
XmlNode node = doc.SelectSingleNode("/note/parent_element/child_element[@attribute_1 = '1']");
node.ParentNode.RemoveChild(node);

如何将所有内容写回到Web应用程序取决于所期望的内容。 我将附上一个针对RESTful Web服务发布XML文件的示例

WebRequest req = WebRequest.Create(updateURL);

req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.Default.GetBytes(xmldoc);
req.ContentLength = bytes.Length;

Stream data = req.GetRequestStream();

data.Write(bytes, 0, bytes.Length);
data.Close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM