My XML File has:
< Package > xmlMetadata < /Package >
I am searching for a tag in this file and the text between the starting and closing tags of this has to be printed on console. i.e. in this case I want xmlMetadata to be printed on the console. Similarly it should go further in the file and print again if it encounters another < Package > tag in the same file.
Here is my code but it is printing the contents of the whole file:
{
string line="< Package >";
ifstream myfile (xmlFileName); //xmlFileName is xml file in which search is to done
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
std::cout<<line<< endl;
}
myfile.close();
}
else cout << "Unable to open file";
}
Displaying below my whole xml:
< ? xml version="1.0" ? >
< fileStructure >
< Main_Package >
File_Navigate
< /Main_Package >
< Dependency_Details >
< Dependency >
< Package >
xmlMetadata
< /Package >
< Header >
xmlMetadata.h
< /Header >
< Header_path >
C:\Dependency\xmlMetadata\xmlMetadata.h
< /Header_path >
< Implementation >
xmlMetadata.cpp
< /Implementation >
< Implementation_path >
C:\Dependency\xmlMetadata\xmlMetadata.cpp
< /Implementation_path >
< /Dependency >
< Dependency >
< Package >
xmlMetadata1
< /Package >
< Header >
xmlMetadata1.h
< /Header >
< Header_path >
C:\Dependency\xmlMetadata\xmlMetadata1.h
< /Header_path >
< Implementation >
xmlMetadata1.cpp
< /Implementation >
< Implementation_path >
C:\Dependency\xmlMetadata\xmlMetadata1.cpp
< /Implementation_path >
< /Dependency >
< /Dependency_Details >
< /fileStructure >
Getline doesn't search for a line it simply reads each line into the variable "line", you then have to search in that "line" for the text you want.
size_t found=line.find("Package");
if (found!=std::string::npos) {
cout << line;
BUT this is a bad way to handle XML - there is nothing stopping the XML writer from breaking the tag onto multiple lines. Unless this is a one off and you create the file you really should use a general XML parser to read the file and give you a list of tags.
There are a bunch of very easy to use XML parsers, such as TinyXML
EDIT (different xml now posted) - that's the problem with using regex to parse xml, you don't know how the xml will break lines. You can keep adding more and more layers of complexity until you have written your own xml parser - just use one of What is the best open XML parser for C++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With