我有以下XML:
<r xmlns:p="p" xmlns:s="s" p:p="1">
<d id="{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}">
<r uid="{B19D0460-69C9-4FEC-A882-41FFA77B582F}" p:before="r[@uid='{D43901A0-1B71-4C65-BEED-DDCF28FCE5A5}']" s:ds="/Polecane" s:id="{C3AC52FB-8F51-4B44-A3EE-55F4C2EAF83F}" s:par="" s:ph="moviesplaceholder" />
<r uid="{D43901A0-1B71-4C65-BEED-DDCF28FCE5A5}" p:before="r[@uid='{4D8EE7B4-E1D2-4CBF-AED7-5E969EFAA57A}']" s:ds="/HITY" s:id="{7A80D822-8D6A-40C4-92D4-2FA22C596339}" s:par="" s:ph="moviesplaceholder" />
<r uid="{4D8EE7B4-E1D2-4CBF-AED7-5E969EFAA57A}" p:before="r[@uid='{B6036949-B723-42CE-9271-64DF299450DC}']" s:ds="/VOD" s:id="{557800E7-953B-4830-8691-3FFB964712A8}" s:par="" s:ph="moviesplaceholder" />
</d>
</r>
我将它存储在String变量中。我可以找到带
的节点吗?s:ds="/Polecane"
然后得到它的&#34; uid&#34;并将其设置在&#34; p:之前&#34;在HITY节点?
答案 0 :(得分:2)
使用XDocument:
string xml = @"<r xmlns:p=""p"" xmlns:s=""s"" p:p=""1"">
<d id=""{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}"">
<r uid=""{B19D0460-69C9-4FEC-A882-41FFA77B582F}"" p:before=""r[@uid='{D43901A0-1B71-4C65-BEED-DDCF28FCE5A5}']"" s:ds=""/Polecane"" s:id=""{C3AC52FB-8F51-4B44-A3EE-55F4C2EAF83F}"" s:par="""" s:ph=""moviesplaceholder"" />
<r uid=""{D43901A0-1B71-4C65-BEED-DDCF28FCE5A5}"" p:before=""r[@uid='{4D8EE7B4-E1D2-4CBF-AED7-5E969EFAA57A}']"" s:ds=""/HITY"" s:id=""{7A80D822-8D6A-40C4-92D4-2FA22C596339}"" s:par="""" s:ph=""moviesplaceholder"" />
<r uid=""{4D8EE7B4-E1D2-4CBF-AED7-5E969EFAA57A}"" p:before=""r[@uid='{B6036949-B723-42CE-9271-64DF299450DC}']"" s:ds=""/VOD"" s:id=""{557800E7-953B-4830-8691-3FFB964712A8}"" s:par="""" s:ph=""moviesplaceholder"" />
</d>
</r>";
XNamespace nsS = "s";
XNamespace nsP = "p";
XDocument xd = XDocument.Parse(xml);
XElement elPolecane = xd.Descendants("r").Where(e => (e.Attribute(nsS + "ds") != null) && e.Attribute(nsS + "ds").Value == "/Polecane").FirstOrDefault();
if (elPolecane != null)
{
string uid = elPolecane.Attribute("uid").Value;
XElement elHITY = xd.Descendants("r").Where(e => (e.Attribute(nsS + "ds") != null) && e.Attribute(nsS + "ds").Value == "HITY").FirstOrDefault();
if (elHITY != null)
{
elHITY.Attribute(nsP + "before").SetValue("r[@uid='" + uid + "']");
}
}
Console.WriteLine(xd.ToString());
Console.ReadLine();
答案 1 :(得分:-1)
您可以使用以下内容:
//variable which holds xml data
string xml = "<r>......</r>";
XmlDocument doc = new XmlDocument();
//XML in XmlDocument
doc.LoadXml(xml);
XmlNodeList nodes = doc.SelectNodes("//d/r");
string uid = "";
//Parse all r nodes
foreach (XmlNode node in nodes)
{
if (node.Attributes["s:ds"].InnerText == "/Polecane")
{
uid = node.Attributes["uid"].InnerText;
}
}
foreach (XmlNode node in nodes)
{
if (node.Attributes["s:ds"].InnerText == "/HITY")
{
//Update attribute
node.Attributes["p:before"].InnerText = uid;
}
}
doc.Save(@"C:\tmp\xmldocument.xml");