I'm using C#.
I have an XmlElement with InnerXml
<b xpage="5" xid="85">3-6. Title</b><i>. The Content</i>
which makes the InnerText as
3-6. Title. The Content
Now I have a match variable with value
3-6. Title.
What i wanted to get is the rest of the portion of InnerXml ..ie.
<i> The Content</i>
Please Help.
It looks like you have two sibling nodes, B and I. To match a specific instance of B, use an XPath text selector.
string xpath = "//*/b[text()='3-6. Title']"; // replace wildcard with real path
http://publib.boulder.ibm.com/infocenter/iseries/v6r1m0/index.jsp?topic=/db2/rbafzxpathqueryexmp.htm
Once you have matched B, you can use the NextSibling property to find I
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.nextsibling.aspx
in the OuterXml property you get the xml string you want <i>. The Content</i>
XmlDocument doc = new XmlDocument();
doc.LoadXml("<rootxml><b xpage=\"5\" xid=\"85\">3-6. Title</b><i>. The Content</i></rootxml>");
XmlNode root = doc.FirstChild;
var completeString = root["b"].OuterXml + root["i"].OuterXml;
if (completeString.StartsWith("3-6. Title.") {
XmlElement xmlElement = root["i"];
var iContent = xmlElement.OuterXml;
Console.WriteLine(iContent);
}
hope this helps
Related
I have a xml like this:
<xmlRootNode>
<levelOneChildNode>
Some text
<levelTwoChildNode>
<levelThreeChildNode>More text</levelThreeChildNode>
</levelTwoChildNode>
</levelOneChildNode>
</xmlRootNode>
I can't change the xml format because my client wants this format. How I should create and decorate "levelOneChildNode" class for a correct serialization? I can't use XmlElement or XmlAttribute. The only way to do this than I've thought is put "Some text" as a XmlElement and make a
string.replace("<textNode>", string.empty).replace("</textNode>", string.empty)
with de serialized xml to remove de tag but this is a crapy solution.
Any ideas without manual xml manipulation?
I guess you have two options, both of them related to manual xml-manipulation:
Use
XmlWriter
to write elements one by one.
Fill general-purpose
XmlDocument,
and save it.
Set/Retrieve/Append/Create XmlNotes (values):
//file name
string filename = #"d:\temp\XMLFile2.xml";
//create new instance of XmlDocument
XmlDocument _doc = new XmlDocument();
//load from file
_doc.Load(filename);
// Change text in xml
XmlNode node= _doc.SelectSingleNode("xmlRootNode/levelOneChildNode"); // [index of user node]
node.InnerText = value;
_doc.Save(#"path");
// Retrive value from xml
XmlNode node = _doc.SelectSingleNode("xmlRootNode/levelOneChildNode/levelTwoChildNode/someAttribute");
string value = node.InnerText;
// read or write to more elements
foreach (XmlNode node in doc.SelectNodes("xmlRootNode/levelOneChildNode/levelTwoChildNode"))
{
string data= node.SelectSingleNode("someAttribute").InnerTex; // get value of someAttribute.
node.InnerText = value;
}
// Append Note to levelOneChildNode Note
// Create second node
XmlNode secondNode = doc.CreateElement("SecondLevelNode");
secondNode .InnerText = "This title is created by code"
XmlNode firstNode= _doc.SelectSingleNode("xmlRootNode/levelOneChildNode");
firstNode.AppendChild(secondNode );
_doc.Save(#"path");
I got this function for simply get the inner text of my xml:
XmlDocument document = new XmlDocument();
document.Load("game.xml");
string content = document.SelectSingleNode("Game/Client-Version").InnerText;
(this is the xml file (due to complications with stackoverflow posted on pastebin)): http://pastebin.com/EEeFAJpC
And now I am exactly looking for the function above, just to write. Like
document.WriteSingleNode("Game/Client-Version", "texttowrite");
I did not find anything helping me out.
This should work
XmlElement x = document.SelectSingleNode("Game/Client-Version") as XmlElement;
x.InnerText = "texttowrite";
Create your own extension method:
public void WriteSingleNode(this XmlDocument document, string NodeName, string InnerText)
{
// Create a new element node.
XmlNode newElem = document.CreateNode("element", "pages", "");
newElem.InnerText = InnerText;
Console.WriteLine("Add the new element to the document...");
document.DocumentElement.AppendChild(newElem);
Console.WriteLine("Display the modified XML document...");
Console.WriteLine(document.OuterXml);
}
I am creating XML document by reading some objects and adding them to proper place (inside xml tree structure). To be able to add it to proper place I need parent XmlNode so I could call parentNode.AppendChild(node);
How can I get XmlNode object if I know value of one of its attributes?
XmlDocument dom = new XmlDocument();
XmlNode parentNode = null;
XmlNode node = dom.CreateElement(item.Title); //item is object that I am writing to xml
XmlAttribute nodeTcmUri = dom.CreateAttribute("tcmUri");
nodeTcmUri.Value = item.Id.ToString();
node.Attributes.Append(nodeTcmUri);
parentNode = ??? - how to get XML node if I know its "tcmUri" attribute value (it is unique value, no other node has same "tcmUri" attribute value)
You can do this using SelectSingleNode function and xpath query as below
XmlNode parentNode = dom.SelectSingleNode("descendant::yournodename[#tcmUri='" + item.Id.ToString() + "']");
Where yournodename has to be replaced with the node name of the parent elements
Try this
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
XmlNodeList list = doc.SelectNodes("mynode");
foreach (XmlNode item in list)
{
if (item.Attributes["tcmUri"].Value == some_value)
{
// do what you want, item is the element you are looking for
}
}
Use following code:
var nodeList = doc.SelectNodes("<Node Name>[#tcmUri = \"<Value>\"]");
if(list.Count>0)
parentNode = list[0];
Replace <Node Name> with the node name which you want to make the parent node.
Replace the <Value> with the value of tcmUri attribute of the Node which you want to make the parent node.
XPath is your friend :
string xpath = String.Format("//parentTag[#tcmUri='{0}']", "tcmUriValueHere");
//or in case parent node name (parentTag) may varies
//you can use XPath wildcard:
//string xpath = String.Format("//*[#tcmUri='{0}']", "tcmUriValueHere");
parentNode = dom.SelectSingleNode(xpath)
i have an xmlnode node2.
XmlNode node2 = sm.UploadXML(xmlFile);
In this node2,node2.innerxml contains the following.
<ContractName>Company Name - yyyy</ContractName><AccountID>123456</AccountID><ContractID>12674</ContractID><NBR>156</NBR><ApplyRateShop>False</ApplyRateShop>
now i want to use the value of ContractID.how can i use it?i am doing in c#
I think this will get you the value you require:
String contractId = node2.SelectSingleNode("ContractID").InnerXml;
As the InnerXml also contains XML, you can access it using the methods of XmlNode. In your case, you can use SelectSingleNode to get a node and then retrieve its value by using the InnerXml property again:
var contractIdNode = node2.SelectSingleNode("ContractID");
var contractId = contractIdNode.InnerXml;
I have a simple XML doc with no Namespace
Here is the code I wrote in C# to search for a particular element based on Name.
public XmlElement SearchXML(string name)
{
XmlDocument xDoc = new XmlDocument();
string filePath = ConfigurationManager.AppSettings["path"];
xDoc.Load(filePath);
string xQryStr = "//NewPatient[Name='" + name + "']";
xDoc.SelectNodes(xQryStr);
XmlElement xmlEle = xDoc.DocumentElement;
return xmlEle;
}
The XML document is as follows
When I try to call the method SearchXML and pass Dennis as the arguement, instead of returning the xml element containing only the specific elements, it returns the entire document.
Where am I possibly erring?
Any help appreciated.
xDoc.SelectNodes(xQryStr) does not mutate the original doc. You need to store the return value of this method call and return that instead.
ATM you're simply returning the root element of the original doc (i.e. the entire tree)
EDIT
In answer to your comment, you could fish the first matched XmlElement as follows:
xDoc.SelectNodes(xQryStr).OfType<XmlElement>().FirstOrDefault()
This will return either null or an XmlElement
If you want to select a list of nodes based on an XPath expression, you need to use .SelectNodes in this fashion:
public XmlElement SearchXML(string name)
{
XmlDocument xDoc = new XmlDocument();
string filePath = ConfigurationManager.AppSettings["path"];
xDoc.Load(filePath);
string xQryStr = "//NewPatient[Name='" + name + "']";
XmlNodeList listOfNodes = xDoc.SelectNodes(xQryStr);
foreach(XmlNode node in listOfNodes
{
// do something with that list of XML nodes you've selected....
// XmlElement xmlEle = node;
// return xmlEle;
}
}
The call to .SelectNodes(xpath) returns a list of matching XML nodes (see the MSDN documentation on XmlDocument.SelectNodes) - once you have that list, you can iterate over the matched nodes and do something with them....
Or if you're expecting only a single XML node to match your XPath expression, you can use .SelectSingleNode, too:
string xQryStr = "//NewPatient[Name='" + name + "']";
XmlNode matchedNode = xDoc.SelectSingleNode(xQryStr);
if(matchedNode != null)
{
// do something with that list of XML nodes you've selected....
return matchedNode;
}
can you change
string xQryStr = "//NewPatient[Name='" + name + "']";
to
xQryStr = "/NewPatient[Name='" + name + "']";
see the below link
http://www.csharp-examples.net/xml-nodes-by-name/