How to check whether xml element contain special word and than remove it (with c#)
I write in C# (asp.net) and make one xml file from many others, but in this files there are element (villageName) with text that I want to change. I want to check whether it contain "c." in the start and than I want to remove it. The tag is repeated many times. Sometimes the value doesn't begin with "c." This is a part of my code. Maybe here I must write the check.
foreach (XmlElement singer in doc.DocumentElement.GetElementsByTagName("singers").Item(0).ChildNodes)
{
开发者_如何学Go foreach (String element in elements)
{
XmlNodeList placeName = singer.GetElementsByTagName(element + "Place");
XmlNodeList areaName = singer.GetElementsByTagName(element + "Area");
if (villageName.Count != 0 && areaName.Count != 0)
{
villages.Add(new AddLocation(villageName.Item(0).InnerText, areaName.Item(0).InnerText));
}
}
}
<singers>
<singer>
<sing>girls</sing>
<gender>woman</gender>
<livePlace>c. Vido </livePlace>
<liveArea>Brabab</liveArea>
</singer>
<singer>
<sing>girls</sing>
<gender>woman</gender>
<livePlace>c. Ido </livePlace>
<liveArea>Sab</liveArea>
</singer>
<singer>
<sing>girls</sing>
<gender>woman</gender>
<livePlace>Vido </livePlace>
<liveArea>Brabab</liveArea>
</singer>
</singers>
This code should do the trick. Where instead of using a node list you reference the root node of whatever you are trying to perform the replacement on. Your code and question are a little unclear so I had to generalize it with the an XmlNodeList.
XmlNodeList nodeList = _xmlDoc.GetElementsByTagName("villageName");
foreach (XmlNode node in nodeList)
{
if (node.InnerXml.Substring(0,1).Contains('c'))
{
node.InnerXml.Remove(0, 1);
}
}
精彩评论